dugla
dugla

Reputation: 12954

NSArray. How do I implement the Map function?

In iOS I want to implement the map function for NSArray. This is a function that is applied to every element of the array. What is the best way to implement this?

Thanks,
Doug

Upvotes: 10

Views: 9613

Answers (3)

Dmytro
Dmytro

Reputation: 1918

If you are using Objective-C, you can simply use these methods:

- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(nullable id)argument;

For example:

[array makeObjectsPerformSelector:@selector(doSomething)];

Upvotes: 0

user156027
user156027

Reputation:

You are looking for apply as map should return a new array with the transformed values.

However you can augment NSArray with the methods you look for by creating a custom category. Here are two examples - apply and map:

@implementation NSArray (CMMap)
- (NSArray *) map:(id(^)(id obj))block {
    NSMutableArray *a = @[].mutableCopy;
    for (id o in self) {
        id on = block(o);
        if (!on) {
            NSLog(@"NSArray::map() - object returned by block is nil!");
            abort();
        }
        [a addObject: on];
    }
    return [NSArray arrayWithArray: a];
}

- (void) apply:(void(^)(id obj))block {
    for (id o in self) {
        block(o);
    }
}
@end

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

You can use enumerateObjectsUsingBlock: function of NSArray.

[myArray enumerateObjectsUsingBlock:^(id x, NSUInteger index, BOOL *stop) {
    // Body of the function
}];

Upvotes: 5

Related Questions