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"];
Written by Jure Žove
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ios
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#