How to skip objects while iterating in a ruby like Map method for obj-c

有些话、适合烂在心里 提交于 2019-12-23 19:46:28

问题


Using the answer here this method achieves something similar to ruby's map in obj-c:

- (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;
}

my question is how can i skip an object if something wrong happens while applying the block? Typically to skip something in an enumerator one just use the return command, however that's not an option in the method above, since the block is expected to return something.

In this example I use return to skip but get an error:

NSArray *mappedArray = [objArray mapObjectsUsingBlock:^(id obj, NSUInteger i) {
    // i don't want this obj to be included in final array
    // so I try to skip it
    return;   // ERROR:incompatible block pointer types sending 
              // 'void(^)(__strong id, NSUInteger)' to parameter of type 
              // 'id(^)(__strong id, NSUInteger)'


    // else do some processing
    return soupedUpObj;
}];

My current way of working around it is simply returning a null object, then removing them out from the final array. But I'm sure there must be a better way than that.


回答1:


If the implementation is similar to what you showed above, it would make sense to just apply the block result to an intermediate value and then check it before adding it to the result array. Something like this:

- (NSArray *)mapObjectsUsingBlock:(id (^)(id obj, NSUInteger idx))block {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id blockResult = block( obj, idx );
        if( result != nil ){
          [result addObject:blockResult];
        }
    }];
    return result;
}



回答2:


One quick remedy: Write your own variant, which uses an NSPointerArray rather than NSArray. NSPointerArray can hold nil. Then order can be preserved, and you may use nil to indicate error (assuming NSNull is a valid value which cannot be used to indicate error). With the NSPointerArray, your block would just return nil.




回答3:


This is simply a limitation of whatever framework or library mapObjectsUsingBlock: comes from (it's not a standard Apple API).

Implementing array map functionality is not difficult however, so you can easily write your own version which handles nil return values from the block argument.



来源:https://stackoverflow.com/questions/18360559/how-to-skip-objects-while-iterating-in-a-ruby-like-map-method-for-obj-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!