What Is Key-Value Coding?
Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. In essence, key-value coding defines the patterns and method signatures that your application’s accessor methods implement.
Implementing key-value coding compliant accessors in your application is an important design principle. Accessors help to enforce proper data encapsulation, isolateto centralized locations, and facilitate integration with other technologies such as key-value observing, Core Data, Cocoa bindings, and scriptability. Key-value coding methods can, in many cases, also be utilized to simplify your application’s code. See Model Object Implementation Guide for more guidance on why your application should implement key-value coding compliant accessors and make use of them.
The essential methods for key-value coding are declared in the
NSKeyValueCodingObjective-C informal protocol and default implementations are provided by
Key-value coding supports properties with object values, as well as the scalar types and structs. Non-object parameters and return types are detected and automatically wrapped, and unwrapped, as described in “Scalar and Structure Support.”
[a setProductName:@"Washing Machine"]
[a setValue:@"Washing Machine" forKey:@"productName"];
[a setValue:[NSNumber numberWithInt:240] forKey:@"voltage"];
some notes from The Big Nerd Ranch Guide:
Note that even though you have no accessor methods for one object, the variable can still be set and read from others methods (via key-value coding). This is an obvious violation of the idea of object encapsulation - methods of an object are public, but the instance variables are delicate and should be kept private. If key-value coding weren't astonishingly useful, no one would tolerate it.