ios - Realm Swift iOS - 无法设置主键

标签 ios swift realm

我会尽可能简短地解释我的场景,我在 Realm GitHub Repo 上阅读了一些关于这个问题的评论:

Terminating app due to uncaught exception 'RLMException', reason: 'Can't set primary key property 'id' to existing value 'xxxxxxx'.

这是我的问题:

我有两个类(class)。

预约模型类

import Foundation
import RealmSwift

class Appointment: Object {

    dynamic var id = 0
    dynamic var user_id: String?
    dynamic var profile_id: String?

    let mainMeeting = List<Meeting>()
    let meetingsWithOtherInfo = List<Meeting>()

    override static func primaryKey() -> String? {
        return "id"
    }
}

session 模型类

import Foundation
import RealmSwift

class Meeting: Object {

    dynamic var id = 0
    dynamic var name: String?
    dynamic var created_at: String?

    // other info
    dynamic var restaurant_venue: String?

    override static func primaryKey() -> String? {
        return "id"
    }
}

我正在像这样从我的服务器 API 获取约会

for fetchedAppointment in allAppointmentsFromAlamofire {
    let existingAppointment: Results<(Appointment)>! = realm.objects(Appointment).filter("id = \(fetchedAppointment["id"]!)")

    let newAppointment: Appointment = Appointment()
    newAppointment.id = fetchedAppointment["id"]! as! Int
    ....

    // add data to Meeting connected to Appointment
    let newMeeting = Meeting()
    newMeeting.id = fetchedAppointment["meetings"]["id"]! as! Int
    ...

    // update or add new entry
    try! realm.write {
        print("NEW APPOINTMENT: \(newAppointment)")
        realm.add(newAppointment, update: existingAppointment.count == 0 ? false : true)
    }
}

每当程序尝试更新 Realm 中的现有条目时,就会出现错误 - 只要 existingAppointment 为 1。这里的解决方法是删除 override static func primaryKey( ) 在 session 类中。

如果我只是向 Appointment 添加新条目没有问题,但是如果我要更新,问题就会再次出现,如果我删除 session 类中的 primaryKey(),问题就会消失 ---- 但是,在我的应用程序的其他屏幕中,我真的需要在 session 类中使用 primaryKey()。

我的疯狂猜测是,每次我需要更新约会中的条目时,我也应该更新 session 。

那么,问题是:为什么会这样?我的疯狂猜测是否正确?还有其他方法可以解决这个问题吗?

最佳答案

看起来您正在尝试使用不是其主键的值更新 newAppointment 对象。

realm.add(newAppointment, update: existingAppointment.count == 0 ? false : true)

相反,Realm 希望您提供该对象的键,以便它可以更新指定的对象。

看起来您正在此处设置键值,这是您应该用于更新的键值。

let newAppointment: Appointment = Appointment()
newAppointment.id = fetchedAppointment["id"]! as! Int

Realm documentation on updating with keys.

关于ios - Realm Swift iOS - 无法设置主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38091738/

相关文章:

ios - 解析实时查询处理错误

ios - 设置自定义数据集值 - 图表 3.0.4 和使用 Swift 4.0

ios - 用户在 iOS 上单击电子邮件中的 url 并被带到应用程序而不是 Web。如何知道网址?

javascript - 页面未在 iOS 的 URLRequest 上重定向

ios - Realm Swift iOS - 安全地删除和重新键入加密的 Realm

ios - 核心数据 - 在一对多关系中分配值

ios - 调整 UICollectionView 的宽度

ios - 在左上角位置的边框上带有标签的 TextField

android - 处理多线程和 Realm 的正确方法是什么?

swift - 在 Realm 中避免重复对象的正确方法?