swift - 在不触及其他(保存的)值的情况下更新 Realm 中的多个属性

标签 swift realm

阅读 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/

相关文章:

swift - 如何在 Swift Quick Nimble 中执行 beforeAll

swift - 了解 AppDelegate 中的保留计数

ios - 将 RLMResults 转换为 RLMArray

ios - 返回对象 Realm 不可访问

ios - “<...> 不是有效的 NSFetchRequest。”

swift - 如何使一个函数只能被特定的类快速调用?

ios - 通过 CocoaPods 安装 Realm

java - 代号一和 Realm 集成

ios - Podspec 在 podfile pod 导入时失败

android - 按日期排序 - Realm (Android)