gpt4 book ai didi

ios - Realm -iOS : Object reference set to nil after save

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:25:59 26 4
gpt4 key购买 nike

我有 2 个类:CompanyEmployee。两者都继承了 Realm Object 类。

class Company:Object {
var name:String = ""
var employee:Employee?

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

class Employee:Object {
var name:String = ""
var age:Int = 0

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

填充对象

    var emp = Employee()
emp.name = "Sachin"
emp.age = 35

var comp = Company()
comp.name = "BCCI"

comp.employee = emp

println("Before: \(comp.employee)")

var realm = Realm()
realm.write {
println("Before Add: \(comp.employee)")
realm.add(comp, update: true)
println("In Block: \(comp.employee)")
}

println("After: \(comp.employee)")

结果:

Before: Employee { name = Sachin; age = 35; }
Before Add: Employee { name = Sachin; age = 35; }
In Block: nil
After: nil

问题:为什么realm.add()操作后Company对象的employee属性为nil?有什么想法吗?

最佳答案

对于所有 Realm Swift 属性(List 除外),您需要将属性声明为dynamic。将您的模型定义更改为以下内容应该会有所帮助!

class Company:Object {
dynamic var name:String = ""
dynamic var employee:Employee?

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

class Employee:Object {
dynamic var name:String = ""
dynamic var age:Int = 0

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

关于ios - Realm -iOS : Object reference set to nil after save,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31118060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com