我会尽可能简短地解释我的场景,我在 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
关于ios - Realm Swift iOS - 无法设置主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38091738/