Last Updated: February 25, 2016
·
676
· jure

Key-Value Coding in Collections

A really cool trick of doing simple collection operation is using Key-Value Coding.

For example, if we have a class Person:

@interface Person : NSObject

@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *age;

+ (Person *)personWithFirstName:(NSString *)firstName
                       lastName:(NSString *)lastName
                            age:(NSNumber *)age;

@end

and an array which holds multiple objects of that type:

Person *first = [Person personWithFirstName:@"Jack"
                                  lastName:@"Doe"
                                       age:@22];
Person *second = [Person personWithFirstName:@"Jane"
                                  lastName:@"Doe"
                                       age:@32];
Person *third = [Person personWithFirstName:@"John"
                                  lastName:@"Doe"
                                       age:@41];
NSArray *people = @[first, second, third];

we can quite easily find the oldest/youngest person or the average age of people in the array:

NSNumber *maxAge = [people valueForKeyPath:@"@max.age"];
NSNumber *minAge = [people valueForKeyPath:@"@min.age"];
NSNumber *avgAge = [people valueForKeyPath:@"@avg.age"];