NSArray Equivalent of Map

后端 未结 11 1800
萌比男神i
萌比男神i 2020-11-28 05:06

Given an NSArray of NSDictionary objects (containing similar objects and keys) is it possible to write perform a map to an array of specified key?

11条回答
  •  天涯浪人
    2020-11-28 05:50

    It only saves a couple lines, but I use a category on NSArray. You need to ensure your block never returns nil, but other than that it's a time saver for cases where -[NSArray valueForKey:] won't work.

    @interface NSArray (Map)
    
    - (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block;
    
    @end
    
    @implementation NSArray (Map)
    
    - (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block {
        NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
        [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [result addObject:block(obj, idx)];
        }];
        return result;
    }
    
    @end
    

    Usage is much like -[NSArray enumerateObjectsWithBlock:]:

    NSArray *people = @[
                         @{ @"name": @"Bob", @"city": @"Boston" },
                         @{ @"name": @"Rob", @"city": @"Cambridge" },
                         @{ @"name": @"Robert", @"city": @"Somerville" }
                      ];
    // per the original question
    NSArray *names = [people mapObjectsUsingBlock:^(id obj, NSUInteger idx) {
        return obj[@"name"];
    }];
    // (Bob, Rob, Robert)
    
    // you can do just about anything in a block
    NSArray *fancyNames = [people mapObjectsUsingBlock:^(id obj, NSUInteger idx) {
        return [NSString stringWithFormat:@"%@ of %@", obj[@"name"], obj[@"city"]];
    }];
    // (Bob of Boston, Rob of Cambridge, Robert of Somerville)
    

提交回复
热议问题