How to set primary key in Swift for Realm model
For Swift 5:
import RealmSwift
class Signature: Object {
@objc dynamic var id = ""
override static func primaryKey() -> String? {
return "id"
}
}
To avoid: Terminating app due to uncaught exception 'RLMException', reason: 'Primary key property 'id' does not exist on object.
The return type of primaryKey()
is optional:
class Foo: RLMObject {
dynamic var id = 0
dynamic var title = ""
override class func primaryKey() -> String? {
return "id"
}
}
As of Realm Swift v10.10.0, you declare a primary key with @Persisted(primaryKey: true)
:
class Foo: Object {
@Persisted(primaryKey: true) var id = 0
@Persisted var title = ""
}
Older versions:
primaryKey
needs to be a class function which returns the name of the property which is the primary key, not an instance method which returns the value of the primary key.
@objcMembers class Foo: RLMObject {
dynamic var id = 0
dynamic var title = ""
override class func primaryKey() -> String? {
return "id"
}
}