Reputation: 35657
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
}
}
Upvotes: 5
Views: 4818
Reputation: 35657
Dynamic
Tells the runtime to use dynamic dispatch over static dispatch for the function or variables modified
Implicitly adds the @objc attribute to the variable or function declaration.
Anything using the dynamic keyword uses the Objective-C runtime instead of the Swift runtime to dispatch messages to it.
Dynamic is useful for app analytics situations but sacrifices optimizations provided by static dispatch.
Dynamic dispatch add better interoperability with Objective-C runtime functions like Core Data which relies on KVC/KVO.
And from the Swift Language Reference
Apply this modifier to any member of a class that can be represented by Objective-C. When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched using the Objective-C runtime. Access to that member is never inlined or devirtualized by the compiler.
Upvotes: 0
Reputation: 18308
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.
Upvotes: 7