What's the standard convention for creating a new NSArray from an existing NSArray?

Posted by Prairiedogg on Stack Overflow See other posts from Stack Overflow or by Prairiedogg
Published on 2009-06-22T09:31:22Z Indexed on 2010/03/29 6:33 UTC
Read the original article Hit count: 325

Filed under:
|
|

Let's say I have an NSArray of NSDictionaries that is 10 elements long. I want to create a second NSArray with the values for a single key on each dictionary. The best way I can figure to do this is:

    NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
    for (NSDictionary *p in array) {
    	[nameArray addObject:[p objectForKey:@"name"]];
    }
    self.my_new_array = array;
    [array release];
    [nameArray release];
}

But in theory, I should be able to get away with not using a mutable array and using a counter in conjunction with [nameArray addObjectAtIndex:count], because the new list should be exactly as long as the old list. Please note that I am NOT trying to filter for a subset of the original array, but make a new array with exactly the same number of elements, just with values dredged up from the some arbitrary attribute of each element in the array.

In python one could solve this problem like this:

new_list = [p['name'] for p in old_list]

or if you were a masochist, like this:

new_list = map(lambda p: p['name'], old_list)

Having to be slightly more explicit in objective-c makes me wonder if there is an accepted common way of handling these situations.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about cocoa-touch