objective-c - NSPredicate代替循环来过滤对象数组

标签 objective-c nspredicate

有人告诉我可以使用 NSPredicate 来复制此方法的结果

- (void) clearArrayOut
{
    bool goAgain = false;

    for (int j=0; j<[array count]; j++)
    {
        if ([[array objectAtIndex:j] someMethod] == NO)
        {
            [array removeObjectAtIndex:j];
            goAgain = true;
            break;
        }
    }

    if (goAgain) [self clearArrayOut];
}

如何制作一个 NSPredicate 来根据自定义类调用的某些方法的结果来过滤数组?

最佳答案

要使用应用的过滤器进行复制:

NSArray *filteredArray = [someArray filteredArrayUsingPredicate:
    [NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
        return [object someMethod]; // if someMethod returns YES, the object is kept
    }]];

就地过滤 NSMutableArray:

[someMutableArray filterUsingPredicate:
    [NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
        return [object someMethod]; // if someMethod returns YES, the object is kept
    }]];

但如果我要过滤一个小数组,我可能只会使用 for 循环。但是,我的 for 循环编写方式略有不同,以避免递减索引变量或递归地调用自己:

- (void)clearArrayOut:(NSMutableArray *)array {
    for (int i = array.count - 1; i >= 0; --i) {
        if (![[array objectAtIndex:i] someMethod]) {
            [array removeObjectAtIndex:i];
        }
    }
}

关于objective-c - NSPredicate代替循环来过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11439492/

相关文章:

ios - 如何在 Objective-C 中过滤自定义对象

ios,获取两个成员变量之一的访问器?

iphone - 苹果单例查询示例?

ios - 转换 __bridge CFType 以支持 ARC

ios - 核心数据 ANY ANY 多 INNER JOIN

ios - 如何在 NSTimeInterval 上使用谓词?

ios - 在 iOS 中搜索自定义对象

objective-c - NSPredicate 的结果作为字符串

ios - 以编程方式默认 iPhone 屏幕截图

ios - 通过 setHighlighted 更新 UITableViewCell