我试图在Swift 2中从Realm查询迭代结果 . 存储了两个PersonClass对象 .
查询的结果var有效并包含两个PersonClass对象,但在迭代结果时,name属性为空字符串 .
class PersonClass: Object {
var name = ""
}
let realm = try! Realm()
@IBAction func button0Action(sender: AnyObject) {
let results = realm.objects(PersonClass)
print(results) //prints two PersonClass object with the name property populated
for person in results {
let name = person.name
print(name) //prints and empty string
}
}
2 回答
问题是您已从模型类中的属性声明中省略了
dynamic
修饰符 .dynamic
修饰符是确保Realm有机会拦截对属性的访问权限所必需的,这使得Realm有机会从磁盘上的文件读取/写入数据 . 省略此修饰符会导致Swift编译器直接访问实例变量,从而将Realm从循环中删除 .动态
告诉运行时对修改的函数或变量使用静态分派的动态分派
将@objc属性隐式添加到变量或函数声明中 .
使用dynamic关键字的任何东西都使用Objective-C运行时而不是Swift运行时来向它发送消息 .
动态对于应用程序分析情况很有用,但牺牲了静态调度提供的优化 .
动态调度增加了与Objective-C运行时函数(如依赖于KVC / KVO的Core Data)的更好的互操作性 .
并从Swift语言参考