Realm ignoredProperties不适用于复合主键

时间:2018-01-04 06:56:33

标签: ios swift realm

我正在尝试从两个键创建复合主键。使用lazy for compoundKey会引发异常 - either remove lazy or add to ignore property list

因此,当我尝试添加忽略属性列表时,我遇到异常 - Terminating app due to uncaught exception 'RLMException', reason: 'Primary key property 'compoundKey' does not exist on object 'Collection'

删除lazy并设置空字符串将添加空键,因此单行将所有主键值视为空。

这是我的代码

class Collection : Object {
    @objc dynamic var count: Int = 0
    @objc dynamic var nextURL: String?
    @objc dynamic var previousURL: String?

    func setCompoundNextURL(nextURL: String) {
        self.nextURL = nextURL
        compoundKey = compoundKeyValue()
    }

    func setCompoundTourPreviousURL(previousURL: String) {
        self.previousURL = previousURL
        compoundKey = compoundKeyValue()
    }

    public dynamic lazy var compoundKey: String = self.compoundKeyValue()

    override static func primaryKey() -> String? {
        return "compoundKey"
    }

    override static func ignoredProperties() -> [String] {
        return ["compoundKey"]
    }

    func compoundKeyValue() -> String {
        return "\(nextURL ?? "")\(previousURL ?? "")"
    }
}

请帮忙。我无法弄清楚我哪里出错了。

1 个答案:

答案 0 :(得分:2)

您不能告诉Realm使用被忽略的属性作为主键。被忽略的属性不会持久存在于Realm中。主键属性必须持久保存到Realm。此外,创建对象后无法更改主键属性的值。出于这个原因,我建议在便利初始化程序中计算值,并在那时将其分配给属性。