NSPredicate: The integrated query language

Often it’s hard to keep up with the all the new cool stuff. Java 6 is around the corner and only one of my projects already uses Java 5.

The same is for Cocoa. Apple is finishing Leopard while I’m still learning APIs and enhancements of Tiger. So was it today when I remembered something from the WWDC that’s called NSPredicate.

In order to find out if an application with a specific bundle identifier (unique key) is running you would do something like this:

int index;
NSArray* apps = [[NSWorkspace sharedWorkspace] launchedApplications];
for(index=0; index < [apps count]; index++) {
    NSString* identifier = [[apps objectAtIndex:index] 
                    objectForKey: @"NSApplicationBundleIdentifier"];
    if ([identifier isEqualToString: someIdentifier]) {
        // do something and leave for loop            
    }
}

Tiger introduced NSPredicate which is used by core data to define queries. But it can also be used to search for items in collections. So doing it with NSPredicate is as simple as this:

[NSPredicate predicateWithFormat:@"NSApplicationBundleIdentifier=%@",
                                 someIdentifier]];
NSArray* apps = [[[NSWorkspace sharedWorkspace] launchedApplications] 
                          filteredArrayUsingPredicate:predicate];
if ([apps count]==1) {
     // do something
}

The real benefit comes of course when your query is more complex. So beside using while or for to filter a collection just take a look at NSPredicate. It can make things a bit easier. Note: Tiger only :-)

One Response to “NSPredicate: The integrated query language”

  1. Keith Duncan Says:

    Interesting, I’m only just learning the ins and outs of Core Data for my own apps and was about to look at NSPredicate for filtering.

    And you are so right about how hard it is to keep up, I’ve just learnt Obj-C 1.0 and I I hear that version two is just around the corner!