What's the Objective-C equivalent of JS's

2019-02-08 15:59发布

问题:

This question already has an answer here:

  • NSArray Equivalent of Map 10 answers

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

回答1:

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



回答2:

It depends. If you have, say, an array of objects, and these objects have a URL property (for example), then you can do:

NSArray * urls = [myArray valueForKey:@"URL"];

Likewise, if you can trigger the behavior of the objects in question via a single message that takes 0 or 1 parameters, you can do:

[myArray makeObjectsPerformSelector:@selector(doFoo)];
//or:
[myArray makeObjectsPerformSelector:@selector(doFooWithBar:) withObject:aBar];

For anything beyond that, you'll have to iterate over the objects yourself. You can use a for() loop, a for(in) loop, or something like -enumerateObjectsUsingBlock:, etc.



回答3:

You do it yourself. There is no single method equivalent to what you want.

Edit: For those downvoting, this was the correct answer at the time (three years ago) and still is for Objective-C, but Swift does have a map() function.



回答4:

Check BlocksKit, it provides map, reduce and filer for NSArray.

  • (NSArray *)map:(BKTransformBlock)block;
  • (id)reduce:(id)initial withBlock:(BKAccumulationBlock)block;
  • (NSArray *)select:(BKValidationBlock)block;


回答5:

Category function for NSArray an alternative

- (NSArray *)map:(id(^)(id, BOOL *))block {
    NSMutableArray * array = [NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id newObject = block(obj,stop);
        if (newObject == nil) {
            newObject = [NSNull null];
        }
        [array addObject:newObject];
    }];
    return array.copy;
}

Category function for NSMutableArray an alternative

- (NSMutableArray *)map:(id(^)(id))block {
    NSEnumerator * enumerator = ((NSArray *)self.copy).objectEnumerator;
    id obj; NSUInteger idx = 0;
    while ((obj = enumerator.nextObject)) {
        self[idx] = block(obj) ?: [NSNull null];
        idx++;
    }
    return self;
}