How to set primary key in Swift for Realm model

末鹿安然 提交于 2019-11-29 15:55:20

问题


I'm using Realm in a new iOS Swift project. I'm using Xcode 6.0.1 with iOS SDK 8.0 and Realm 0.85.0

I'm trying to use the new Realm primary key feature so I can do an addOrUpdateObject.

Here is a sample model:

import Foundation
import Realm

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

    func primaryKey() -> Int {
        return id
    }
}

And how I'm trying to add/update a new object:

let foo = Foo()
foo.title = titleField.text
foo.id = 1

// Get the default Realm
let realm = RLMRealm.defaultRealm()

// Add to the Realm inside a transaction
realm.beginWriteTransaction()
realm.addOrUpdateObject(foo)
realm.commitWriteTransaction()

I get this error:

RLMExecption', reason: ''Foo' does not have a primary key and can not be updated

Here are the docs on the primary key. I'm probably not setting it correctly: http://realm.io/docs/cocoa/0.85.0/api/Classes/RLMObject.html#//api/name/primaryKey

Latest docs are here now: https://realm.io/docs/objc/latest/api/Classes/RLMObject.html#//api/name/primaryKey


回答1:


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"
    }
}



回答2:


The return type of primaryKey() is optional:

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

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



回答3:


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.



来源:https://stackoverflow.com/questions/26152254/how-to-set-primary-key-in-swift-for-realm-model

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