Using NSPredicate to Filter an NSArray

Marc Charbonneau mentioned an upcoming feature for C# which allows you to filter an array using an arbitrary expression. It turns out you can already do something very similar using NSArray and NSPredicate.

NSPredicate is a new class in Tiger which you can use to build queries for Spotlight and Core Data. You can also use it on basic arrays. Here's a simple example:

NSArray * myArray;
myArray = [NSArray arrayWithObjects:
              @"Cupertino",
              @"Sunnyvale",
              @"Mountain View",
              @"Palo Alto", nil];

NSPredicate * predicate;
predicate = [NSPredicate predicateWithFormat:@"length == 9"];
NSArray  * myArray2 = [myArray filteredArrayUsingPredicate:predicate];

NSLog(@"myArray2: %@", myArray2);


Which results in:

myArray2: (Cupertino, Sunnyvale, "Palo Alto")

The predicate is applied to the contents of the array, and the ones that pass the test are added to the new array. Keep in mind that "length" just refers to the NSString "length" attribute, not something special for NSPredicate.

You can build much more complex predicates using the Predicate Programming Guide and the doc on Predicate format strings. NSPredicate's regular expression matching uses the ICU regex syntax.
Design Element
Using NSPredicate to Filter an NSArray
Posted Nov 10, 2006 — 5 comments below




 

Christian — Nov 11, 06 2387

Or you can use the predicate expression builder which ships with Xcode. I definitly use it to create more complex predicates.

mmalc — Nov 11, 06 2389

See also the Filtering Arrays section in Arrays: Ordered Collections of Objects.

Alastair Tse — Nov 13, 06 2393

Neat! Thanks for that little tidbit.

Mithras — Nov 16, 06 2417

One step closer to Smalltalk, I guess. Sure would be nice to have real blocks, though, wouldn't it?

Boyd — Sep 11, 09 6860

@Mithras: Ask and ye shall receive. Eventually. :)




 

Comments Temporarily Disabled

I had to temporarily disable comments due to spam. I'll re-enable them soon.





Copyright © Scott Stevenson 2004-2015