在 IOS Realm Primary key 中,如何更新数据,如果已经存在,应该不需要两次?

In IOS Realm Primary key, how to update data and if already exist it should not take twice?

有了那个 primaryKey offerName 如何避免重复数据两次或更多次。

当我们使用那个对象的didSelectRowAt时如何编辑它并更新数据到它的对象,而不是在我们更新时将它作为新对象。

我该怎么做?

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 { [=10=].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

Realm 提供了几种更新对象属性的方法。

很多答案取决于用例 - 对于此示例,您似乎正在尝试更新已知对象的 属性 而不是现有主键。

从 DiscountClass 开始 - 一种想法是 offerName 可能不是一个好的主键;如果您有两个名称相同的优惠,“10% Off”很常见怎么办?您最好使用 UUID,然后将报价作为对象中的文本。

class DiscountClass: Object {
    @objc dynamic var discount_id = UUID().uuidString //guaranteed unique
    @objc dynamic var offerName : String = ""
    @objc dynamic var percentage: Float = 0.00
    override class func primaryKey() -> String? {
        return "discount_id"
    }
}

根据您的问题,这些看起来像是显示在列表(tableView?)中,由数据源支持,通常是数组,对于 Realm,Results 对象也能正常工作。

var discountResults = Results<DiscountClass>

当用户选择要编辑的行时,该行索引将对应于 discountResults 中的索引。我不知道你是如何编辑的,所以我们只说当用户选择一行时,他们就可以编辑百分比。完成后,更新非常简单

try! realm.write {
    thisDiscount.percentage = "0.1" //updates this objects percent to 10%
}

因为它是一个已知对象,所以您专门更新了该对象的百分比,它不会创建另一个对象。

如果您处于添加新对象而不是更新现有对象的情况,那么您可以利用 realm.create 选项并为更新参数提供 .modified 或 .all .注意 .all 可能有很多开销,所以通常 .modified 是首选。

请记住,要使用 realm.create,您需要创建对象并分配一个现有的主键(如果您想要更新),或者如果您想要创建一个新的唯一主键。

有关更多示例和完整说明,请参阅文档:Updating objects with primary keys