Realm Swift 组合键用于可选属性



有什么方法可以为具有可选属性的 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 文档中找不到有关可选主键的任何内容。

您需要设置RealmOptionalvalue成员。 RealmOptional属性不能被var,因为 Realm 无法检测到对不能由 Objective-C 运行时表示的属性类型的赋值,这就是为什么RealmOptionalListLinkingObjects属性都必须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)"
    }
}

最新更新