javascriptobjective-cporting

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


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


Solution

  • 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.)