Dus*_*tin 2 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];
}
Run Code Online (Sandbox Code Playgroud)
如何NSPredicate根据自定义类调用的某些方法的结果来过滤数组?
rob*_*off 10
要应用过滤器制作副本:
NSArray *filteredArray = [someArray filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
return [object someMethod]; // if someMethod returns YES, the object is kept
}]];
Run Code Online (Sandbox Code Playgroud)
要过滤NSMutableArray到位:
[someMutableArray filterUsingPredicate:
[NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
return [object someMethod]; // if someMethod returns YES, the object is kept
}]];
Run Code Online (Sandbox Code Playgroud)
但for如果我过滤一个小数组,我可能只会使用一个循环.但是,我会for以不同的方式编写我的循环,以避免不得不递减索引变量或递归调用自己:
- (void)clearArrayOut:(NSMutableArray *)array {
for (int i = array.count - 1; i >= 0; --i) {
if (![[array objectAtIndex:i] someMethod]) {
[array removeObjectAtIndex:i];
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3095 次 |
| 最近记录: |