Objective-c – transparent process creation for cocoa components


I have an application A which may or may not need to spawn an application B and will communicate with it using remote messaging (via NSConnections etc.).

While i know how to do this if B is started first, i wonder:
What is a clean cocoa-based approach of transparently starting B on demand?

(For those familiar with COM, i am effectively looking for a CoCreateInstance() equivalent)

Best Solution

If this is a GUI app, you could do something like this for 10.6:

NSArray * runningBs = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.example.B"];
if ([runningBs count] == 0) {
  NSURL * bURL = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:@"com.example.B"];
  NSRunningApplication * b = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:bURL options:NSWorkspaceLaunchDefault configuration:nil error:nil];

For 10.5:
Use -[NSWorkspace launchedApplications] and iterate through the array to see if you find B.
If you don't, find the [NSWorkspace absolutePathForAppBundleWithIdentifier:] and then use one of the [NSWorkspace launchApplication:] varieties.