I am trying to iterate over Results from a Realm query in Swift 2. There are two PersonClass objects stored.
The results var from the query is valid and contains two PersonClass objects but when iterating over results, then name property are empty strings.
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
}
}
The problem is that you have omitted the dynamic
modifier from the property declaration in your model class. The dynamic
modifier is necessary to ensure that Realm has an opportunity to intercept access to the properties, giving Realm an opportunity to read / write the data from the file on disk. Omitting this modifier results in the Swift compiler accessing the instance variables directly, cutting Realm out of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With