领域添加具有复合主键错误的对象

Realm Adding Object with Compound primaryKey Error

我有一个简单的class

class FarmRecord: Object {
    dynamic var year = ""
    dynamic var month = ""
    dynamic var day = ""

    func setYearID(inYear: String) {
        self.year = inYear
        compoundKey = compoundKeyValue()
    }
    func setMonthID(inMonth: String) {
        self.month = inMonth
        compoundKey = compoundKeyValue()
    }
    func setDayID(inDay: String) {
        self.day = inDay
        compoundKey = compoundKeyValue()
    }


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

    private func compoundKeyValue() -> String {
        return "\(year)\(month)\(day)"
    }

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

我尝试按如下方式添加对象:

let storeRealm = try! Realm()
let farm = FarmRecord()
farm.setYearID("2016")
farm.setMonthID("3")
farm.setDayID("1")
do {
    try storeRealm.write {
        storeRealm.add(farm)
    }
} catch {
}

我看到 EXEC_BAD_ACCESS (code = 1) 崩溃了。我什至试过 storeRealm.add(farm, update: true) 没有任何区别。

Realm 似乎对您的 compoundKey 属性 处理不当,因为它被标记为 lazy。我写了一个bug report about the issue on GitHub。作为解决方法,我建议删除 lazy 修饰符并将 compoundKey 初始化为空字符串。