NSPredicate: The integrated query language
Tuesday, October 24th, 2006Often 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
