Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over Results in Realm with Swift

Tags:

swift

realm

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   
  }
}
like image 739
Jay Avatar asked Aug 06 '16 17:08

Jay


1 Answers

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.

like image 180
bdash Avatar answered Oct 22 '22 03:10

bdash