ios - 检查后尝试使用现有主键创建对象的 RLMException

标签 ios swift realm

由于以下原因,我收到了 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/

相关文章:

ios - 使用 CIFilter 应用于 UIImage 和旋转图像的过滤器

ios - 使用 HTTP header 参数发布请求

swift - Realm ,将字符串保存\更新\观察到 Realm 对象的最佳方法

Iphone UITableView、单元格和通知 - 通知后单元格未显示正确的图像

ios - 本地化应用程序因 NSRangeException 而崩溃

ios - 如何区分 UIScrollView 中的平移和滚动

ios - 如何使用 Realm Swift 将旧属性迁移到新对象中

javascript - 将 Iframe 嵌入图像内

ios - Swift - 有没有办法在特定时间唤醒我的应用程序?

ios - 如何在 Realm 中实现继承(iOS、Objective C)