views:

114

answers:

1

I found there are at least three ways to launch an app with Mac OS X from an application.

  1. NSTask. I can give parameters, but it seems that it's not for an Cocoa App, but an UNIX style binary.
  2. system function (system()) just the same way as C does. I don't know the reason why but it seems that nobody recommends this method.
  3. NSWorkspace, but I can't find a way to pass parameters to this function.

Questions

  • Q1 : Is there any other way to launch an App (from an App) other than three methods?
  • Q2 : What's the pros and cons for each method?
  • Q3 : What's the preferable way for launching an App (from an App)?
  • Q4 : What's the preferable way for launching an App with parameters (from an App)?
  • Q5 : What's the preferable way to open a document (from an App)?

ADDED

  • NSWorkspace openFile:withApplication: : For running "TextMate README.txt", based on Roadmaster's answer and this code, I could make it as follows. But, I can't give the parameters to the App.
    NSString * path = @"/Users/smcho/Desktop/README.txt";
    NSURL * fileURL = [NSURL fileURLWithPath: path];
    NSWorkspace * ws = [NSWorkspace sharedWorkspace];
    [ws openFile:[fileURL path] withApplication:@"TextMate"];
  • NSWorkspace launchApplicationAtURL:options: : It works with 10.6 or later, you can get an example from this question.
    NSURL * bURL = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:@"com.macromates.textmate"];
    NSWorkspace * ws = [NSWorkspace sharedWorkspace];
    [ws launchApplicationAtURL:bURL options:NSWorkspaceLaunchDefault configuration:nil error:nil];
  • NSTask : This is the working code. I need to give the correct binary path, and it doesn't look like a Cocoa way, as it's for running binary, not bundle. Though, it's possible to give more parameters than just a file name.
    [NSTask launchedTaskWithLaunchPath:@"/Applications/TextMate.app/Contents/MacOS/TextMate"     arguments:[NSArray arrayWithObjects:@"hello.txt", nil]];
  • system() : With the shell, I could run "system(open -a ABC --args hello.txt)", just like I do with the command line. It seems that this is the easiest way to go.
+2  A: 

In 10.6 and later, NSWorkspace has a method launchApplicationAtURL:options:configuration:error: that can be used to pass arguments to the app.

There are also Launch Services functions such as LSOpenItemsWithRole.

You could also send an AppleEvent to the Finder asking it to open something.

EDIT TO ADD: "best" is subjective, but I'd say if you can use NSWorkspace, use it. If you can't, e.g., you need to pass command-line parameters and you need to support Leopard, then use Launch Services.

JWWalker