Key-Value Coding
Key-Value Coding (KVC) lets you read and write an object's properties by name, using strings, instead of calling the accessors directly. It's defined on NSObject, so every class supports it. KVC powers sort descriptors, Cocoa bindings, Core Data and Interface Builder, and it makes some generic code remarkably short.
valueForKey: and setValue:forKey:
#import <Foundation/Foundation.h>
@interface Book : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic) NSInteger year;
@property (nonatomic) double rating;
@end
@implementation Book
@end
int main(void) {
@autoreleasepool {
Book *b = [Book new];
[b setValue:@"Dune" forKey:@"title"];
[b setValue:@"Frank Herbert" forKey:@"author"];
[b setValue:@1965 forKey:@"year"]; // NSNumber is unboxed into NSInteger
[b setValue:@4.5 forKey:@"rating"];
for (NSString *key in @[@"title", @"author", @"year", @"rating"]) {
NSLog(@"%@ = %@", key, [b valueForKey:key]); // NSInteger is boxed back
}
NSLog(@"direct access still works: %ld", (long)b.year);
}
return 0;
}title = Dune
author = Frank Herbert
year = 1965
rating = 4.5
direct access still works: 1965
KVC automatically boxes and unboxes scalar values: year is an NSInteger, but through KVC it's an NSNumber.
Dictionaries in and out
Two handy methods convert between objects and dictionaries:
#import <Foundation/Foundation.h>
@interface Contact : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *email;
@property (nonatomic) NSInteger age;
@end
@implementation Contact
@end
int main(void) {
@autoreleasepool {
NSDictionary *row = @{@"name": @"Ola", @"email": @"ola@example.com", @"age": @29};
Contact *c = [Contact new];
[c setValuesForKeysWithDictionary:row]; // fill from a dictionary
NSLog(@"%@ <%@>, %ld", c.name, c.email, (long)c.age);
c.age += 1;
NSDictionary *out = [c dictionaryWithValuesForKeys:@[@"name", @"age"]];
NSLog(@"name: %@, age: %@", out[@"name"], out[@"age"]);
}
return 0;
}Ola <ola@example.com>, 29
name: Ola, age: 30
Key paths
A key path follows a chain of properties with dots, like order.customer.city:
#import <Foundation/Foundation.h>
@interface Address : NSObject
@property (nonatomic, copy) NSString *city;
@end
@implementation Address
@end
@interface Customer : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Address *address;
@end
@implementation Customer
@end
int main(void) {
@autoreleasepool {
Customer *cust = [Customer new];
cust.name = @"Tomas";
cust.address = [Address new];
[cust setValue:@"Porto" forKeyPath:@"address.city"];
NSLog(@"%@ lives in %@", cust.name, [cust valueForKeyPath:@"address.city"]);
cust.address = nil;
NSLog(@"without an address: %@", [cust valueForKeyPath:@"address.city"]);
}
return 0;
}Tomas lives in Porto
without an address: (null)
A nil link in the path just gives nil, thanks to nil messaging.
Collection operators
Called on an array, valueForKey: returns an array of each element's value. Key paths can also contain collection operators starting with @:
#import <Foundation/Foundation.h>
@interface Item : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *category;
@property (nonatomic) double price;
+ (instancetype)name:(NSString *)n category:(NSString *)c price:(double)p;
@end
@implementation Item
+ (instancetype)name:(NSString *)n category:(NSString *)c price:(double)p {
Item *i = [self new];
i.name = n; i.category = c; i.price = p;
return i;
}
@end
int main(void) {
@autoreleasepool {
NSArray *cart = @[[Item name:@"Pen" category:@"office" price:1.5],
[Item name:@"Mug" category:@"kitchen" price:8],
[Item name:@"Pad" category:@"office" price:3.5],
[Item name:@"Bowl" category:@"kitchen" price:6]];
NSArray *names = [cart valueForKey:@"name"];
NSLog(@"names: %@", [names componentsJoinedByString:@", "]);
NSLog(@"count: %@", [cart valueForKeyPath:@"@count"]);
NSLog(@"sum: %@", [cart valueForKeyPath:@"@sum.price"]);
NSLog(@"avg: %@", [cart valueForKeyPath:@"@avg.price"]);
NSLog(@"max: %@", [cart valueForKeyPath:@"@max.price"]);
NSLog(@"min: %@", [cart valueForKeyPath:@"@min.price"]);
NSArray *cats = [cart valueForKeyPath:@"@distinctUnionOfObjects.category"];
NSLog(@"categories: %@", [[cats sortedArrayUsingSelector:@selector(compare:)] componentsJoinedByString:@", "]);
}
return 0;
}names: Pen, Mug, Pad, Bowl
count: 4
sum: 19
avg: 4.75
max: 8
min: 1.5
categories: kitchen, office
| Operator | Result |
|---|---|
@count |
number of elements |
@sum.key, @avg.key |
total / average of a numeric property |
@max.key, @min.key |
largest / smallest value |
@distinctUnionOfObjects.key |
unique values (no order) |
@unionOfObjects.key |
all values, duplicates kept |
Unknown keys
A key that doesn't match any property raises NSUnknownKeyException. A class can override setValue:forUndefinedKey: / valueForUndefinedKey: to handle that, which is useful when loading data with extra fields:
#import <Foundation/Foundation.h>
@interface Settings : NSObject
@property (nonatomic, copy) NSString *theme;
@end
@implementation Settings
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"ignoring unknown key '%@'", key);
}
@end
@interface Strict : NSObject
@property (nonatomic, copy) NSString *theme;
@end
@implementation Strict
@end
int main(void) {
@autoreleasepool {
NSDictionary *json = @{@"theme": @"dark", @"zoom": @2};
Settings *s = [Settings new];
[s setValuesForKeysWithDictionary:json];
NSLog(@"theme: %@", s.theme);
@try {
[[Strict new] setValuesForKeysWithDictionary:json];
} @catch (NSException *e) {
NSLog(@"Strict raised %@", e.name);
}
}
return 0;
}ignoring unknown key 'zoom'
theme: dark
Strict raised NSUnknownKeyException
Note: KVC trades compile-time checking for flexibility: a typo in a key string is only found at run time. Use it where flexibility pays off (generic code, sorting, data mapping), and normal property access everywhere else.
NSStringFromSelector(@selector(title))gives you a key string that the compiler checks.
Test yourself
What does [book valueForKey:@"year"] return when year is an NSInteger property?
- An NSInteger
- An NSNumber
- An NSString
- nil
What does [items valueForKeyPath:@"@sum.price"] compute?
- The number of items
- The total of every item's price
- The most expensive price
- An array of prices
Which exception does KVC raise for a key that doesn't exist?
- NSRangeException
- NSUnknownKeyException
- NSInvalidArgumentException
- None, it returns nil