有什么方法可以为具有可选属性的 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 Documentation ,我需要将可选属性设置为常量。
我不确定这是否可行,因为我在 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)"
}
}
关于swift - 可选属性的 Realm Swift 复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44210863/