Quick Array Access Using Key Value Coding

May 29, 2014

Reading time ~1 minute

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 Persons and want all their names. You could create a mutable array, iterate the array of Persons, 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 names 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"
)

The Day I Was Hacked

It was 4am on a Saturday in 2013 and I was sleeping. My iPhone was sitting on my bedside table, plugged in in silent mode. It buzzed once...… Continue reading

Siri Remote - The Future of Gaming?

Published on September 20, 2015

Open Source Is Not 'Do What You Want'

Published on April 29, 2015