如何使用Swift迭代Realm中的结果

Jay*_*Jay 5 realm swift

我试图在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   
  }
}
Run Code Online (Sandbox Code Playgroud)

bda*_*ash 7

问题是您dynamic已从模型类中的属性声明中省略了修饰符.该dynamic修改是必要的,以确保该领域有机会拦截访问的属性,给境界机会阅读/从磁盘上的文件写入数据.省略此修饰符会导致Swift编译器直接访问实例变量,从而将Realm从循环中删除.