请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-11 16:51:34 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我会尽量简短地解释我的场景,我已经阅读了 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap