Archive for April 5th, 2009

05
Apr

KVC Key Paths

If you just haven’t gotten around yet to sorting out what this funky KVC stuff in Objective-C is all about, here’s a good article explaining just how helpful — insanely helpful, to quote a phrase — they can be.

How would you use this in the real world? What if you had a shockingly descriptive object model of your friends and you wanted to find all of your friends who had a dad named “Bob”. No problem with key paths! Just throw in this NSArray category and you are set!

@implementation NSArray (Find)

- (NSArray *)findAllWhereKeyPath:(NSString *)keyPath equals:(id)value {
    NSMutableArray *matches = [NSMutableArray array];
    for (id object in self) {
        id objectValue = [object valueForKeyPath:keyPath];
        if ([objectValue isEqual:value] || objectValue == value) [matches addObject:object];
    }

    return matches;
}

@end

// Implementation example
NSArray *friendsWithDadsNamedBob = [friends findAllWhereKeyPath:@"father.name" equals:@"Bob"]

Yep, that is mildly nifty, isn’t it? But here’s the seriously nifty stuff that we’d managed to overlook so far:

But that’s not all! key paths have magic keywords you can throw in like sumdistinctUnionOfObjects and avg.

NSArray *animals = [NSArray arrayWithObjects:@"pig",
  @"dog",
  @"human",
  @"bear",
  @"frog",
  nil];

NSLog(@"Sum: %@", [animals valueForKeyPath:@"@sum.length"]);
NSLog(@"Avg: %@", [animals valueForKeyPath:@"@avg.length"]);

// Sum: 19
// Avg: 3.8

Didn’t know just how nifty this KVC stuff can be, didja?

h/t: iPhoneKicks!