First off, we need to learn some vocabulary:
- property - an object value (specifically attributes, to-one relationships, and to-many relationships) that can be accessed by KVC.
- attribute - a property that is represented as a simple value. Examples include immutable (non-editable) objects, numbers, strings, booleans, etc.
- to-one relationship - a property in which an object has properties of its own
- to-many relationship - a property that consists of a collection of related objects, such as an NSArray
- key - a string that identifies a specific property of an object.
@interface AppleFruit : NSObject
{
NSNumber *price;
}
@property(copy, readwrite) NSNumber *price;
@end
@implementation AppleFruit
@synthesize price;
@end;
Of course, you could get a lot fancier with properties, but there's the bare basics of it.
Now, let's get further acquainted with keys. Keys typically correspond to the name of an accessor method or an instance variable in an object. Quoting the documentation,
Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace.If you wanted to get the value of a key, you would simply use the valueForKey: method. For example:
[appleFruit setValue:23 forKey:price];
[priceTextField setStringValue:[appleFruit valueForKey:price]];
could be used in another class to set and get the price value of the appleFruit object, respectively.
Here's what the class could look like if key-value coding weren't implemented in it:
@interface AppleFruit : NSObject
{
NSNumber *price;
}
- (NSNumber *)returnPrice;
- (void)setPrice:(NSNumber *)newPrice;
@end
@implementation AppleFruit
- (NSNumber *)returnPrice
{
return price;
}
- (void)setPrice:(NSNumber *)newPrice
{
price = newPrice;
}
@end;
See how much code was spared? Good luck with implementing KVC in your applications!
Note: this is a summarized beginner-friendly version of the first three sections of the Key-Value Coding Programming Guide available through Apple's documentation. Bits were also taken from the Design Guidelines and The Objective-C 2.0 Programming Language.


