Search code examples
cocoacocoa-design-patterns

How does KVC in Cocoa check whether an instance variable is accessable?


Recently i was reading "Cocoa Design Patterns". When talking about KVC, it said "KVC check if an accessor named -<key> or -get<Key> exists first, if not, it will try instance variable named <key> or _<key>". Can obj-c runtime check whether an instance variable exist? I think it can only be done in compile time...

Any answers are appreciated ^_^


Solution

  • It can indeed. The relevant documentation for this is the Objective-C Runtime Reference; specifically, class_getInstanceVariable. The part the documentation leaves out is that that function returns NULL when instances of the class have no such variable.

    KVC, presumably, passes the object's class and the candidate variable names to that function, and the first name for which the runtime comes up with an Ivar is the one it uses.