What's the Objective-C equivalent of JS's `map()` function?

Moshe picture Moshe · Jan 19, 2011 · Viewed 14.7k times · Source

What's the Objective-C equivalent of JS's map() function? Would I just use NSFastEnumeration and apply the function myself?

Answer

mipadi picture mipadi · Jan 20, 2011

You can use NSArray's enumerateObjectsUsingBlock: if you're on OS X 10.6 or iOS 4.:

NSMutableArray *mapped = [NSMutableArray arrayWithCapacity:[array count]];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    id mapObj = DoSomethingToObject(obj);
    [mapped addObject:mapObj];
}];

(Shameless but relevant plug: I have a library for OS X and iOS that adds map and other similar functionality to NSArray and NSSet.)