NSArray Equivalent of Map

后端 未结 11 1807
萌比男神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:55

    I'm no Ruby expert so I'm not 100% confident I'm answering correctly, but based on the interpretation that 'map' does something to everything in the array and produces a new array with the results, I think what you probably want is something like:

    NSMutableArray *replacementArray = [NSMutableArray array];
    
    [existingArray enumerateObjectsUsingBlock:
        ^(NSDictionary *dictionary, NSUInteger idx, BOOL *stop)
        {
             NewObjectType *newObject = [something created from 'dictionary' somehow];
             [replacementArray addObject:newObject];
        }
    ];
    

    So you're using the new support for 'blocks' (which are closures in more general parlance) in OS X 10.6/iOS 4.0 to perform the stuff in the block on everything in the array. You're choosing to do some operation and then add the result to a separate array.

    If you're looking to support 10.5 or iOS 3.x, you probably want to look into putting the relevant code into the object and using makeObjectsPerformSelector: or, at worst, doing a manual iteration of the array using for(NSDictionary *dictionary in existingArray).

提交回复
热议问题