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.
Using NSPredicate to Filter an NSArray
Posted Nov 10, 2006 — 5 comments below
Posted Nov 10, 2006 — 5 comments below
Christian — Nov 11, 06 2387
mmalc — Nov 11, 06 2389
Alastair Tse — Nov 13, 06 2393
Mithras — Nov 16, 06 2417
Boyd — Sep 11, 09 6860