Realm-iOS:保存后对象引用设置为nil

我有两个class: 公司员工 。 两者都inheritance了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)") 

结果:

之前:员工{name = Sachin; 年龄= 35岁; }
之前添加:员工{name = Sachin; 年龄= 35岁; }
座位:无
之后:没有

问题:为什么在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" } }