阅读 docs 时,它说我应该执行以下操作以通过字典更新单个(或多个)字段:
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'
我想动态更新字典中的多个字段,这可能吗?
最佳答案
我不认为该教程是正确的,即使它来自 Realm 工程师编写的官方网站。如果您查看 official documentation在 RealmSwift 中,您可以看到 add
的两个版本函数接受参数子类化 Object
.
您要找的并且应该在教程中提到的函数是public func create<T: Object>(_ type: T.Type, value: Any = [:], update: Bool = false) -> T
,您可以使用它从 Dictionary
更新现有对象.
您的代码应如下所示:
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.create(Person.self, value: person, update: true)
}
关于swift - 在不触及其他(保存的)值的情况下更新 Realm 中的多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609513/