有什么方法可以为具有可选属性的 Realm 类制作复合键吗?
例如:
class Item: Object {
dynamic var id = 0
let importantNumber = RealmOptional<Int>()
let importantNumber2 = RealmOptional<Int>()
func setCompoundID(id: Int) {
self.id = id
compoundKey = compoundKeyValue()
}
func setCompoundImportantNumber(importantNumber: Int) {
self.importantNumber = importantNumber
compoundKey = compoundKeyValue()
}
func setCompoundImportantNumber2(importantNumber2: Int) {
self.importantNumber2 = importantNumber2
compoundKey = compoundKeyValue()
}
dynamic lazy var compoundKey: String = self.compoundKeyValue()
override static func primaryKey() -> String? {
return "compoundKey"
}
func compoundKeyValue() -> String {
return "(id)(importantNumber)(importantNumber2)"
}
}
当我这样编写代码时,编译器抱怨我无法分配给常量属性,并建议我将 'let' 更改为 'var';但是,根据 Realm Swift 文档,我需要将可选属性设置为常量。
我不确定这是否可能,因为我在 Realm 文档中找不到有关可选主键的任何内容。
您需要设置RealmOptional
的value
成员。 RealmOptional
属性不能被var
,因为 Realm 无法检测到对不能由 Objective-C 运行时表示的属性类型的赋值,这就是为什么RealmOptional
、List
和LinkingObjects
属性都必须let
的原因。
class Item: Object {
dynamic var id = 0
let importantNumber = RealmOptional<Int>()
let importantNumber2 = RealmOptional<Int>()
func setCompoundID(id: Int) {
self.id = id
compoundKey = compoundKeyValue()
}
func setCompoundImportantNumber(importantNumber: Int) {
self.importantNumber.value = importantNumber
compoundKey = compoundKeyValue()
}
func setCompoundImportantNumber2(importantNumber2: Int) {
self.importantNumber2.value = importantNumber2
compoundKey = compoundKeyValue()
}
dynamic lazy var compoundKey: String = self.compoundKeyValue()
override static func primaryKey() -> String? {
return "compoundKey"
}
func compoundKeyValue() -> String {
return "(id)(importantNumber)(importantNumber2)"
}
}