Jay Jay - 1 year ago 217
Swift Question

How to iterate over Results in Realm with Swift

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download