NSPredicate 而不是循环来过滤对象数组 [英] NSPredicate instead of loop to filter an array of objects
本文介绍了NSPredicate 而不是循环来过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人告诉我我可以使用 NSPredicate
来复制这个方法的结果
I have been told that I can use NSPredicate
to duplicate the results of this method
- (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
来根据自定义类调用的某些方法的结果过滤数组?
How can I make an NSPredicate
that will filter an array based on the results of some method of a custom class's call?
推荐答案
要制作应用过滤器的副本:
To make a copy with the filter applied:
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
循环,以避免减少索引变量或递归调用自己:
But I would probably just use a for
loop if I were filtering a small array. However, I'd write my for
loop a little differently to avoid having to either decrement the index variable or call myself recursively:
- (void)clearArrayOut:(NSMutableArray *)array {
for (int i = array.count - 1; i >= 0; --i) {
if (![[array objectAtIndex:i] someMethod]) {
[array removeObjectAtIndex:i];
}
}
}
这篇关于NSPredicate 而不是循环来过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文