由于以下原因,我收到了 RLMException
:
Attempting to create an object of type 'Student' with an existing primary key value '258975085-504336622-62850'.
令人困惑的部分是,它是在检查 Realm 中不存在具有此键的现有对象之后发生的。
let realm = try Realm()
if let info = realm.object(ofType: Student.self, forPrimaryKey: newStudent.userId) {
try realm.write {
info.name = newStudent.name
info.school = newStudent.school
info.email = newStudent.email
}
}
else {
try realm.write {
realm.add(newStudent) //RLMException occurs here
}
}
此代码全部在 GCD 实用程序队列上异步运行,位于 do/catch block 内。它由用户界面中的按钮触发,但没有其他任何东西同时访问 Realm 。
为什么 if 语句允许 else 代码运行?
最佳答案
try! self.realm.write {
self.realm.add(newStudent, update: true)
}
您正在添加具有现有主键的相同对象(学生)。所以你可以只更新当前的。而不是删除和添加新的。
关于ios - 检查后尝试使用现有主键创建对象的 RLMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49026513/