Issue
I try create objects in Realm with unique id. I use this code:
class Persons: Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
override static func primaryKey() -> String? {
return "id"
}
}
and in my StorageManager I use this code:
import RealmSwift
let realm = try! Realm()
class StorageManager {
static func saveObject(_ person: Persons) {
try! realm.write {
realm.add(person)
}
}
static func deleteObject(_ person: Persons) {
try! realm.write {
realm.delete(person)
}
}
}
But when I add second new object, I get error:
Terminating app due to uncaught exception ‘RLMException’, reason:
‘Attempting to create an object of type ‘Persons’ with an existing
primary key value ‘0’.’
How I can get new unique id for each new object?
Solution
You’re best bet is to let your code define that for you
class PersonClass: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var name = ""
override static func primaryKey() -> String? {
return "id"
}
}
UUID().uuidString returns a unique string of characters which are perfect for primary keys.
HOWEVER
That won’t work for Realm Sync in the future. MongoDB Realm is the new product and objects need to have a specific primary key property called _id which should be populated with the Realm ObjectID Property. So this is better if you want future compatibility
class PersonClass: Object {
@objc dynamic var _id = ObjectId()
@objc dynamic var name = ""
override static func primaryKey() -> String? {
return "_id"
}
}
You can read more about it in the MongoDB Realm Getting Started Guide
Note that after RealmSwift 10.10.0, the following can be used to auto-generate the objectId
@Persisted(primaryKey: true) var _id: ObjectId
Keeping in mind that if @Persisted
is used on an object then all of the Realm managed properties need to be defined with @Persisted
Answered By – Jay
Answer Checked By – Candace Johnson (BugsFixing Volunteer)