领域 – 不能用现有的主键值创build对象

我有一个对象有很多狗的人。 应用程序有单独的页面,只显示狗和其他页面,显示人的狗

我的模型如下

class Person: Object { dynamic var id = 0 let dogs= List<Dog>() override static func primaryKey() -> String? { return "id" } } class Dog: Object { dynamic var id = 0 dynamic var name = "" override static func primaryKey() -> String? { return "id" } } 

我有人存储在领域。 人有详细信息页面,我们取和显示他的狗。 如果狗已经存在,我更新该狗的最新信息,并将其添加到人的狗列表,否则创build新的狗,保存并添加到人名单。 这工作在coredata。

 // Fetch and parse dogs if let person = realm.objects(Person.self).filter("id =\(personID)").first { for (_, dict): (String, JSON) in response { // Create dog using the dict info,my custom init method if let dog = Dog(dict: dict) { try! realm.write { // save it to realm realm.create(Dog, value:dog, update: true) // append dog to person person.dogs.append(dog) } } } try! realm.write { // save person realm.create(Person.self, value: person, update: true) } } 

在试图用他的狗更新人时,领域抛出exception无法用现有的主键值创build对象

这里的问题是,即使你正在创build一个全新的Realm Dog对象,你实际上并没有把它保存到数据库中,所以当你调用append ,你试图添加第二个副本。

当您调用realm.create(Dog, value:dog, update: true) ,如果具有该ID的对象已经存在于数据库中,则只需使用您创build的dog实例中的值更新该现有对象,但那个dog实例还是一个独立的副本; 它不是数据库中的Dog对象。 您可以通过检查dog.realm是否等于零来确认。

所以当你调用person.dogs.append(dog) ,因为dog不在数据库中,Realm试图创build一个全新的数据库条目,但是因为已经有一个带有该ID的狗,所以失败了。

如果要将该dog对象附加到某person ,则需要查询Realm以检索引用数据库中条目的正确的dog对象。 谢天谢地,对于由主键支持的Realm对象,这非常简单,因为您可以使用Realm.object(ofType:forPrimaryKey:)方法:

 if let person = realm.object(ofType: Person.self, forPrimaryKey: "id") { for (_, dict): (String, JSON) in response { //Create dog using the dict info,my custom init method if let dog = Dog(dict: dict) { try! realm.write { //save it to realm realm.create(Dog, value: dog, update: true) //get the dog reference from the database let realmDog = realm.object(ofType: Dog.self, forPrimaryKey: "id") //append dog to person person.dogs.append(realmDog) } } } try! realm.write { //save person realm.create(person .self, value: collection, update: true) } }