NSArray and KVC
Even more on simplifying code with generic programming! NSArray's -valueForKey: has a feature that may not be immediately obvious. You can use it to return an array of values buried within a tree of objects. Here's a working example:
NSMutableArray * tree = [NSMutableArray array];
NSDictionary * p = nil; // parent
NSDictionary * c = nil; // child
NSNumber * n = nil; // value
int i;
for ( i = 0; i < 10; i++ )
{
n = [NSNumber numberWithInt: i];
c = [NSDictionary dictionaryWithObject: n
forKey: @"someKey"];
p = [NSDictionary dictionaryWithObject: c
forKey: @"storage"];
[tree addObject: p];
}
NSLog (@"%@", tree);
// here's the important part!
NSArray * justValues;
justValues = [tree valueForKeyPath: @"storage.someKey"];
NSLog (@"%@", justValues);
The first NSLog spits this out -- just a two-level property list:
NSLog (@"%@", tree);
(
{storage = {someKey = 0; }; },
{storage = {someKey = 1; }; },
{storage = {someKey = 2; }; },
{storage = {someKey = 3; }; },
{storage = {someKey = 4; }; },
{storage = {someKey = 5; }; },
{storage = {someKey = 6; }; },
{storage = {someKey = 7; }; },
{storage = {someKey = 8; }; },
{storage = {someKey = 9; }; }
)
The second NSLog spits out an array of values collected by asking each contained object for the value at @"storage.someKey":
NSArray * justValues;
justValues = [tree valueForKeyPath: @"storage.someKey"];
NSLog (@"%@", justValues);
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
I find this really convenient in Core Data when working with a sorted array of managed objects -- you can pull out an array of values for just one attribute.