使用primaryKey offerName如何避免重复两次或更多次数据。
[当我们使用该对象的didSelectAtRow时如何编辑它并将数据更新到其对象,而不是在更新时将其当作新对象。
我该怎么办?
import Foundation
import RealmSwift
class Discount: Object {
@objc dynamic var offerName : String = ""
@objc dynamic var percentage: Float = 0.00
@objc dynamic var segmentIndex : Int = 0
@objc dynamic var dateWise: Date?
override class func primaryKey() -> String? {
return "offerName"
}
}
这是一个使用主键更新现有对象的代码片段
guard let realm = try? Realm() else {
return
}
let discounts = realm.objects(Discount.self)
try? realm.write {
discounts.forEach { $0.dateWise = Date() }
realm.add(discounts, update: .all)
}
检查方法文档:
/**
Adds all the objects in a collection into the Realm.
- see: `add(_:update:)`
- warning: This method may only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to the Realm.
- parameter update: How to handle
without a primary key.
- parameter update: How to handle objects in the collection with a primary key that alredy exists in this
Realm. Must be `.error` for object types without a primary key.
*/
public func add<S: Sequence>(_ objects: S, update: UpdatePolicy = .error) where S.Iterator.Element: Objec