swift - 可选属性的 Realm Swift 复合键

标签 swift realm

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

最佳答案

您需要设置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)"
    }
}

关于swift - 可选属性的 Realm Swift 复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44210863/

相关文章:

swift - UIAlertAction 在其回调中关闭 UIAlertController

realm - 如何让keycloak导出 Realm 用户然后退出

ios - 在 iOS 上从服务器缓存和加载数据

java - 使用 Swift 在 iOS 和 Android 之间共享核心代码

xcode - 无法在单独的项目中引用类型

android - Realm 字符串大于

swift - 返回 Realm 中任何可以删除的对象

android - 即使数据存在于 RealmDB 中,Realm where 子句也会返回 0

ios - 解析 : Erase User Account and Session

ios - 顶部导航栏已禁用