iphone - 如何在像 obj-c 的 Map 方法这样的 ruby​​ 中迭代时跳过对象

标签 iphone ios objective-c cocoa objective-c-blocks

使用答案 here此方法实现了类似于 obj-c 中 ruby​​ 的映射:

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

我的问题是,如果在应用 block 时发生错误,我该如何跳过对象? Typically要跳过枚举器中的某些内容,只需使用 return 命令,但这不是上述方法中的一个选项,因为该 block 预计会返回一些内容。

在这个例子中我使用return 来跳过但是得到一个错误:

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

我目前的解决方法是简单地返回一个空对象,然后将它们从最终数组中移除。但我确信一定有比这更好的方法。

最佳答案

如果实现与您在上面展示的类似,则只需将 block 结果应用于中间值然后在将其添加到结果数组之前检查它是有意义的。像这样:

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

关于iphone - 如何在像 obj-c 的 Map 方法这样的 ruby​​ 中迭代时跳过对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18360559/

相关文章:

ios - 从 UITableView 在线保存数据的最佳方法是什么?

ios - 无法设置自定义对象的值

iPhone UIActionSheet

ios - 通过点击 iOS 中的其他位置,超链接的悬停状态不会消失

ios - 尽管响应代码为 200,Instagram api 未返回任何关注者

objective-c - 搜索 NSString 是否包含值

ios - UIButton Touchdown 在 IOS 7 中是否过于敏感?

iPhone -- MKReverseGeocoder.adminstrativeArea -- 获取状态缩写

iphone - 奇怪的 UINavigationController 导航栏行为是否是由于内存泄漏造成的?

ios - PJSIP 视频通话