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"];

In this case there is no advantage to using key–value coding over just calling the accessors. But suppose we had received the value @"number" in a variable (as the result of a method call, perhaps). Suppose that variable is called something. Then we could say:

id result = ...

Get Programming iOS 4 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.