【问题标题】:Updating Realm Object With Primary Key (Swift)使用主键更新领域对象 (Swift)
【发布时间】:2018-08-26 09:41:20
【问题描述】:

我正在尝试使用主键更新/添加到 Realm 数据库。我使用 Realm 文档中的这段代码 sn-p:

var person = ["personID": "My-Primary-Key", "name": "Tom Anglade"]

// Update `person` if it already exists, add it if not.
let realm = try! Realm()
try! realm.write {
    realm.add(person, update: true)
}

但是当我尝试实现它时,它会返回这个错误:

Cannot convert value of type '[String : String]' to expected argument type 'Object'

我有点卡在这里,所以非常感谢任何帮助!

【问题讨论】:

    标签: swift realm primary-key


    【解决方案1】:

    您使用的方法不支持使用 Dictionary 进行更新,我认为您尝试使用 create(_:value:update:) 版本。

    try! realm.write {
        realm.create(Person.self, value: person, update: true) // here person is dictionary with attributes for updating person
    }
    

    您也可以使用add(_:update:) 方法,但它要求您将Realm Object 传递给它。

    let person = Person()
    person.name = dict["name"]
    ... 
    let realm = try! Realm()
    try! realm.write {
        realm.add(person, update: true) // here person is Object of type Person 
    }
    

    Here 是 Realm 官方文档。

    【讨论】:

    • 第一种方法效果很好。令人困惑的是(至少对我而言)Realm 在此页面上对它的描述不同:academy.realm.io/posts/realm-primary-keys-tutorial 但是,嘿,现在它可以工作了,谢谢!
    • 'add(_:update:)' 已弃用:传递 .error、.modified 或 .all 而不是布尔值。 .error 等价于 false,.all 等价于 true。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多