How to set primary key in Swift for Realm model

坚强是说给别人听的谎言 提交于 2019-11-30 10:45:23

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.

class Foo: RLMObject {
    dynamic var id = 0
    dynamic var title = ""

    override class func primaryKey() -> String? {
        return "id"
    }
}

The return type of primaryKey() is optional:

class Foo: RLMObject {
    dynamic var id = 0
    dynamic var title = ""

    override class func primaryKey() -> String? {
        return "id"
    }
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!