I found there are at least three ways to launch an app with Mac OS X from an application.
- NSTask. I can give parameters, but it seems that it's not for an Cocoa App, but an UNIX style binary.
- 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.
- 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.