I want to use a command-line with a argument to call my cocoa app , but in my cocoa app ,how to receive the argument , this argument is a file path, thank you very much!
Neat thing: use NSUserDefaults
.
If you do:
./MyCocoaApp -argument /path/to/file.txt
Then in your code you can do:
NSDictionary * arguments = [[NSUserDefaults standardUserDefaults] volatileDomainForName:NSArgumentDomain];
NSString * path = [arguments objectForKey:@"argument"];
The key
is the -argument
switch, and the value is the thing that comes after it. Note that this isn't very flexible (you can't do combine options: -a -l
≠ -al
), but for rudimentary arguments, this is dead simple.
edit with multiple arguments:
./MyCocoaApp -arg1 42 -arg2 "Hello, world!" -arg3 /path/to/file.txt
And then extract via:
... = [arguments objectForKey:@"arg1"];
... = [arguments objectForKey:@"arg2"];
... = [arguments objectForKey:@"arg3"];
The normal main function in Cocoa passes the command line arguments to NSApplicationMain. The arguments are ignored by NSApplicationMain, but you are free to parse them as needed. There are a few standard ways to parse command line arguments, like getopt, or you can just access the values directly.
int main( int argc , char **argv ) {
if ( argc == 2 ) gPathArgument = argv[1];
NSApplicationMain( argc , argv );
}
Note that launch services may pass command line arguments when an application is opened normally, for example when double clicked in the Finder. Be sure to handle unrecognized arguments.
In the special case of a file path to an existing file you can use open
like this:
open -a /path/to/your.app /path/to/the/file
And then implement this in your application delegate:
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename;