In Cocoa, there are two primary ways to access an object's properties: statically using direct invocations of accessor methods and dynamically using key-value coding (KVC). KVC defines generic property accessor methods—valueForKey: and setValue:forKey:—which identify properties with string-based keys. KVC is not meant as a general alternative to using accessor methods—it is for use by code that has no other option, because the code cannot know the names of the relevant properties at compile time.
Key-value coding and declared properties are orthogonal technologies. You can use KVC whether or not you use properties, and you can use properties whether or not you use KVC. Both, though, make use of a “dot syntax”. In the case of KVC, the syntax is used to delimit elements in a key path. It is important to remember that when you directly access a property using the dot syntax, you invoke the receiver’s standard accessor methods (as a corollary, to emphasize, the dot syntax does not result in invocation of KVC methods valueForKey: or setValue:forKey:).
You can use KVC methods to access a property, for example, given a class defined as follows:
@interface MyClass |
@property NSString *stringProperty; |
@property NSInteger integerProperty; |
@property MyClass *linkedInstance; |
@end |
you could access the properties in an instance using KVC:
MyClass *myInstance = [[MyClass alloc] init]; |
NSString *string = [myInstance valueForKey:@"stringProperty"]; |
[myInstance setValue:[NSNumber numberWithInt:2] forKey:@"integerProperty"]; |
To illustrate the difference between the properties dot syntax and KVC key paths, consider the following.
MyClass *anotherInstance = [[MyClass alloc] init]; |
myInstance.linkedInstance = anotherInstance; |
myInstance.linkedInstance.integerProperty = 2; |
This has the same result as:
MyClass *anotherInstance = [[MyClass alloc] init]; |
myInstance.linkedInstance = anotherInstance; |
[myInstance setValue:[NSNumber numberWithInt:2] |
forKeyPath:@"linkedInstance.integerProperty"]; |
Last updated: 2008-02-05