Reputation: 59
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?
Upvotes: 2
Views: 6531
Reputation: 35658
Your 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
Note if using @Persisted then the override static func primaryKey()
function is not needed
Upvotes: 5
Reputation: 17969
The better answer since Realm v10 came out is to use the dedicated new objectID class
A 12-byte (probably) unique object identifier.
ObjectIds are similar to a GUID or a UUID, and can be used to uniquely identify objects without a centralized ID generator. An ObjectID consists of:
ObjectIds are intended to be fast to generate. Sorting by an ObjectId field will typically result in the objects being sorted in creation order.
Upvotes: 1