There are loads of ways to do this, but by far the neatest is surely using [NSPredicate predicateWithBlock:]
:
NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
return [object shouldIKeepYou]; // Return YES for each object you want in filteredArray.
}]];
I think that's about as concise as it gets.
For those working with NSArray
s in Swift, you may prefer this even more concise version:
let filteredArray = array.filter { $0.shouldIKeepYou() }
filter
is just a method on Array
(NSArray
is implicitly bridged to Swift’s Array
). It takes one argument: a closure that takes one object in the array and returns a Bool
. In your closure, just return true
for any objects you want in the filtered array.