How to call a cocoa app from command-line outside?

陌路散爱 提交于 2020-01-02 19:12:06

问题


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!


回答1:


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"];



回答2:


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;


来源:https://stackoverflow.com/questions/3115302/how-to-call-a-cocoa-app-from-command-line-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!