Key–Value Coding

Cocoa derives the name of an accessor from a string name through a mechanism called key–value coding, or simply KVC. (See also Chapter 5, where I introduced key–value coding.) The key is a string (an NSString) that names the value to be accessed. The basis for key–value coding is the NSKeyValueCoding protocol, an informal protocol (it is actually a category) to which NSObject (and therefore every object) conforms. Key–value coding is a big subject; see the Key-Value Coding Programming Guide for full information.

The fundamental key–value coding methods are valueForKey: and setValue:forKey:. When one of these methods is called on an object, the object is introspected. In simplified terms, first the appropriate accessor is sought; if it doesn’t exist, the instance variable is accessed directly.

So, for example, suppose the call is this:

[myObject setValue:@"Hello" forKey:@"greeting"];

First, a method setGreeting: is sought in myObject; if it exists, it is called, passing @"Hello" as its argument. If that fails, but if myObject has an instance variable called greeting (or _greeting), the value @"Hello" is assigned directly to that ivar.

Warning

The key–value coding mechanism can bypass completely the privacy of an instance variable! Cocoa knows that you might not want to allow that, so a class method accessInstanceVariablesDirectly is supplied, which you can override to return NO (the default is YES).

Both valueForKey: and setValue:forKey: require an object as the value. ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.