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 — 6 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. :)

Contact Center — Jan 28, 10 7254

I just came over here from your other post about NSArrays, and I am wondering if having too many arrays will hold up your server? Is there an amount of NSArrays that is too many, and how much server resources do you need for this?




 

Add Your Thoughts

Use UBB tags: [b] [i] [url] [code], and so on
Use [i] for quoting: [i]Quoted Text[/i]
Omit double quotes in links: [url=http://apple.com]Apple[/url]
Accented characters are currently stripped from names



Please enter the company who makes the Mac:
this is an anti-spam measure
Some comments may be edited for formatting, or removed if too far off-topic.




Technorati Profile
Copyright © Scott Stevenson 2004-2008