'Realm - Can't create object with existing primary key value
I have a object Person with many dogs. App has separate page where it shows just dogs and other page where it shows person's dogs
My model is as follows
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"
}
}
I have persons stored in Realm. Person has detail page where we fetch and show his dogs. If dog already exist, I update latest info for that dog and add it to person's dog list else create new dog, save it and add it to persons list. This works in 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)
}
}
On trying to update person with his dogs,realm throws exception Can't create object with existing primary key value
Solution 1:[1]
Latest API solution:
Use add(_:update:).
try realm.write {
realm.add(objects, update: Realm.UpdatePolicy.modified)
// OR
realm.add(object, update: .modified)
}
Realm.UpdatePolicy enums:
error (default)
modified //Overwrite only properties in the existing object which are different from the new values.
all //Overwrite all properties in the existing object with the new values, even if they have not changed
NB: Works on Realm Swift 3.16.1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
