Have an array full of objects and would like to get, for example, all the names from those objects without having to iterate?
You have a Person
object that has a property name
and you have an array full of Person
s and want all their names. You could create a mutable array, iterate the array of Person
s, access the name
property, store it in your new array, etc. etc. etc.
With Key value Coding, you can ask the array for the values for a given key and it will return a new array containing all the values for each object.
[personArray valueForKey:@"name"];
Voila! A new array containing all the name
s of each Person
object!
For completeness, here's a rather contrived, self-contained, compilable example:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end
@implementation Person
- (id)initWithName:(NSString *)name
{
if ((self = [super init]))
{
self.name = name;
}
return self;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSMutableArray *personArray = [NSMutableArray array];
for (NSInteger i = 1; i < 21; i++)
{
Person *obj = [[Person alloc] initWithName:[NSString stringWithFormat:@"obj %zd", i]];
[personArray addObject:obj];
}
NSLog(@"%@", [personArray valueForKey:@"name"]);
}
}
and the output:
KVCExample[79283:507] (
"obj 1",
"obj 2",
"obj 3",
"obj 4",
"obj 5",
"obj 6",
"obj 7",
"obj 8",
"obj 9",
"obj 10",
"obj 11",
"obj 12",
"obj 13",
"obj 14",
"obj 15",
"obj 16",
"obj 17",
"obj 18",
"obj 19",
"obj 20"
)