Мария G
Мария G

Reputation: 59

How I can get new unique id for each new object in Realm?

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

Answers (2)

Jay
Jay

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

Andy Dent
Andy Dent

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:

  • A 4 byte timestamp measuring the creation time of the ObjectId in seconds since the Unix epoch.
  • A 5 byte random value
  • A 3 byte counter, initialized to a random value.

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

Related Questions