views:

139

answers:

2

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)

+1  A: 

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.

Dave DeLong
This looks neat, but we have to support 10.5. Any pointers to solutions for that? I assume with GUI app you mean Application Kit based?
Georg Fritzsche
@gf - yes, because `NSWorkspace` is an AppKit class. 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.
Dave DeLong
I should also add that if either A or B is a non-bundle app, then @Chuck's approach is better.
Dave DeLong
Thanks, will check it out tomorrow.
Georg Fritzsche
... took the liberty of editing the 10.5 information into the answer.
Georg Fritzsche
+2  A: 

If the other application is a command-line app or can behave like one, NSTask is the best choice — you can launch another program and define its standard input, output and error streams. If this is a GUI app, you can use Scripting Bridge or NSWorkspace + use your own communication protocol with NSConnection, etc.

Chuck
They are GUI apps, but good to know about `NSTask`.
Georg Fritzsche