如何在Swift for Realm模型中设置主键 [英] How to set primary key in Swift for Realm model
问题描述
我在一个新的iOS Swift项目中使用Realm。我正在使用Xcode 6.0.1与iOS SDK 8.0和Realm 0.85.0
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
我正在尝试使用新的Realm主键功能,所以我可以做一个 addOrUpdateObject
。
I'm trying to use the new Realm primary key feature so I can do an addOrUpdateObject
.
以下是一个示例模型:
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()
我收到此错误:
RLMExecption',原因:''Foo'没有主键,不能更新
RLMExecption', reason: ''Foo' does not have a primary key and can not be updated
以下是主键上的文档。我可能没有正确设置:
http://realm.io/docs/cocoa/0.85.0/api/Classes/RLMObject.html#//api/name/primaryKey
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
最新文档现在在这里:
https://realm.io/docs/objc/latest/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
推荐答案
primaryKey
需要是一个类函数,它返回作为主键的属性的名称,而不是实例方法返回主键的值。
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"
}
}
这篇关于如何在Swift for Realm模型中设置主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!