Reputation: 4533
Realm relies on dynamic dispatch to access ObjectiveC runtime for some KVC mechanisms. Model properties should be marked with dynamic
keyword to enable KVC that is used by Realm
objects to fill them with exact values. So you can have model defined like this:
class Car: Object {
dynamic var color = ""
dynamic var age = 0
}
At some level you would be able to set properties like this:
var car = Car()
car["color"] = "white"
car["age"] = 20
This works for all basic types like Int
or String
but doesn't work with generic classes and structures since they can't be represented in Objective C. Realm uses two of those types:
When adding properties of these types to the Realm models, you add them without dynamic keyword:
let cars = List<Car>
let registration = RealmOptional<String>
What mechanism Realm uses to set and read data of those types without using dynamic dispatch?
Update 1
Upon some inspection, I've found that Realm uses some Objective C runtime methods like class_copyPropertyList()
and property_getName()
for introspection of property names. What I haven't found yet is how properties are populated with correct data when you read from Realm? Is that part of the ObjectStore
C++ framework?
Upvotes: 2
Views: 348
Reputation: 10573
Generic properties such like List<T>
or RealmOptional<T>
cannot be appeared from Objective-C. Realm uses Swift's reflection (Mirror()
) to inspect those.
Then directly access their ivar
: https://github.com/realm/realm-cocoa/blob/76d1018b32ba98babce31afbefd31863075cde8c/Realm/RLMObjectSchema.mm#L217-L223
These generic properties are dispatched statically. Realm cannot hook accessing those. That's why those properties must be declared as let
. Realm cannot see re-assign the properties.
Upvotes: 1