有人告诉我可以使用 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/