Cocoa Tip: Filtering NSArray using NSPredicate

Today I 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:

1
2
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.

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.

One Response to “Cocoa Tip: Filtering NSArray using NSPredicate”

  1. I’ve actually found that it’s significantly faster to iterate through a set/array using fast enumeration. Predicates are great for complex situations (like parent/child groupings, etc), but they’re not as fast for very simple comparisons like you’re doing here.

Leave a Reply