领域使用复合primaryKey错误添加对象

时间:2016-03-16 00:36:51

标签: swift primary-key realm

我有一个简单的课程

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)没有区别。

1 个答案:

答案 0 :(得分:1)

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