Key–Value Coding

Objective-C provides a means for translating from a string to an instance variable accessor, called key–value coding. Such translation is useful, for example, when the name of the desired instance variable will not be known until runtime. So instead of calling [fido number], we might have a string @"number" that tells us what accessor to call. This string is the “key.” The key–value coding equivalent of calling a getter is valueForKey:; the equivalent of calling a setter is setValue:forKey:.

Thus, for example, suppose we wish to get the value of the number instance variable from the fido instance. We can do this by sending valueForKey: to fido. However, even though the number instance variable is an int, the value returned by valueForKey: is an object — in this case, an NSNumber, the object equivalent of a number (see Chapter 10). If we want the actual int, NSNumber provides an instance method, intValue, that lets us extract it:

NSNumber* num = [fido valueForKey: @"number"];
int n = [num intValue];

Similarly, to use key–value coding to set the value of the number instance variable in the fido instance, we would say:

NSNumber* num = [NSNumber numberWithInt:42];
[fido setValue: num forKey: @"number"];

Before handing off the number 42 as the value argument in setValue:forKey:, we had to wrap it up as an object — in this case, an NSNumber object. Starting with LLVM compiler version 4.0 (Xcode 4.4), there’s a syntactic shorthand for doing that; just as we can create an NSString ...

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.