Search code examples
iosdatabaserealm

What's best way to prevent duplicating object in Realm?


I have next error: Attempting to create an object of type 'TypeId' with an existing primary key value '96292'. And I got crash after this.


Solution

  • Using String type for the primary key instead of the Int type, and use UUID for each object, then you could avoid the duplicated keys.

    class AModel: Object {
        @objc dynamic var id = UUID().uuidString
    
        override static func primaryKey() -> String? {
            return "id"
        }
    }
    

    Alternatively, if you want to use Int, and you are sure about that there is only one object will be created in a second, you could use timestamp value to avoid the situation too:

    class AModel: Object {
        @objc dynamic var id = Date().timeIntervalSince1970
    
        override static func primaryKey() -> String? {
            return "id"
        }
    }
    

    Agree with @Tj3n and @EpicPandaForce's opinions, updating it if it's not a new object actually.