OGeek|极客世界-中国程序员成长平台

标题: ios - Realm Swift iOS - 无法设置主键 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 16:51
标题: ios - Realm Swift iOS - 无法设置主键

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

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

这是我的问题:

我有两个类。

约会模型类

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。从我从 Github Realm 中读到的解决方法是删除 override static func primaryKey( ) 在 session 课上。

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

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

所以,问题是:为什么会发生这种情况?我的猜测正确吗?还有什么办法可以解决吗?



Best Answer-推荐答案


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

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

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

您似乎在此处设置键值,这是您应该用于更新的键值。

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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4