Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

ios - How to set primary key in Swift for Realm model

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...