Friday, September 28, 2012

What Is Key-Value Coding?


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.
Accessor methods, as the name suggests, provide access to your application’s data model’s property values. There are two basic forms of accessor—get accessors and set accessors. Get accessors, also referred to as getters, return the values of a property. Set accessors, also referred to as setters, set the value of a property. There are getter and setter variants for dealing with both object attributes and to-many relationships.
Implementing key-value coding compliant accessors in your application is an important design principle. Accessors help to enforce proper data encapsulation, isolatememory management to 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 NSKeyValueCoding Objective-C informal protocol and default implementations are provided by NSObject.
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.”

examples:
Object types:
[a setProductName:@"Washing Machine"]
[a setValue:@"Washing Machine" forKey:@"productName"];

[a valueForKey:@"productName"]

Non-object types
[a setVoltage:240];
[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.

Charbonneau is correct. I get an XML feed in which corresponds to an object on the iPhone/Mac client. Typically it'll be something like Bob43 I had a method before that would key/value code NSDictionary instances. – Coocoo4Cocoa Dec 18 '08 at 20:53

No comments:

Post a Comment