有很多种方式都可以实现,但目前最简洁的方式一定是使用 [NSPredicate predicateWithBlock:]:
NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
return [object shouldIKeepYou]; // 要保留就返回 YES。
}]];
相当简明扼要。
Swift
对于在 Swift 中使用 NSArray 的人,你会喜欢这个还要更加简洁的版本:
nsArray = nsArray.filter { $0.shouldIKeepYou() }
filter 只是 Array 的一个方法(NSArray 被隐式桥接到 Swift 的 Array)。只要一个参数:带有数组中某个对象的闭包,返回 Bool 型。在闭包中想保留就返回 true。
