Vincent Gable

September 20, 2008

Regex Matching and Filtering in Cocoa With NSPredicate

Filed under: Cocoa, MacOSX, Objective-C, Programming — Tags: , , , — Vincent Gable @ 2:21 pm

Apples documentation of Regular Expressions With NSPredicate has the full scoop, but basically you do
[NSPredicate predicateWithFormat:@"SELF MATCHES regex-here“];. Unfortunately, you can only test if strings match a regex. You can not use an NSPredicate-regex to extract parts of a string. Depending on what you need to do, this may or may not be enough to save the day.

August 22, 2008

Is an Application Running?

Filed under: Cocoa, MacOSX, Objective-C, Programming, Sample Code, UNIX — Tags: , , — Vincent Gable @ 7:22 pm

Pass in the bundle-identfier of an application, and this will tell you if it’s currently running or not:
- (BOOL) thereIsARunningApplicationWithBundleID:(NSString*)bundleID
{
   NSPredicate   *hasBundleID = [NSPredicate predicateWithFormat:@”%K == %@”, @”NSApplicationBundleIdentifier”, bundleID];
   NSArray *allApps = [[NSWorkspace sharedWorkspace] launchedApplications];
   return 0 != [[allApps filteredArrayUsingPredicate:hasBundleID] count];
}

(It’s a good idea to test if an application is running before sending it an AppleEvent, because that will launch it.)

-thereIsARunningApplicationWithBundleID:will not tell you if a process is running, because -[NSWorkspace launchedApplications] only returns the kind of application that show up in the dock.

Use the Process Manager to find out about running daemons and things without a bundle-ID. Unfortunately, doing this is much more brittle. There’s nothing preventing a user from renaming a file, or a developer unknowingly naming their programs so they conflict with your code. Bundle-Identifiers insulate you from all of this.

Interestingly, none of these API’s can see into another user’s process-space; but ps can; at least on OS X 10.5 and 10.4.

Powered by WordPress