Cocoa Tip: Filtering NSArray using NSPredicate
Today I’ve had a small task in one of my projects – to get subset of elements from NSArray. I’ve already started writing all this NSEnumerator’s stuff (need to support 10.4) when I remembered about NSPredicator. So, instead of iterating over an array and finding elements that satisfy some condition and adding them to some output array you just need to create predicate and filter your input array with it. Here is the sample code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"storeState == 1"]; NSArray *outputArray = [inputArray filteredArrayUsingPredicate:predicate];
Predicates language seems to be very powerful and simple. But I can’t tell you anything about performance, need to investigate.
UPDATE If you want to filter array with regular expressions just use a predicate like this one:
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexp];
Further reading: Apple Predicates Programming Guide
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
![[Facebook]](http://ivira.name/blog/wp-content/plugins/bookmarkify/facebook.png)
![[Twitter]](http://ivira.name/blog/wp-content/plugins/bookmarkify/twitter.png)
![[Email]](http://ivira.name/blog/wp-content/plugins/bookmarkify/email.png)