在Objective C中启动命令行

时间:2014-09-25 10:53:10

标签: objective-c cocoa command-line command-line-arguments nstask

我想在objective-C中执行此命令行,以便从另一个应用程序启动应用程序:

open -n myApp.app --args arg1 arg2

我设法在没有争论的情况下做到了:

    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *myAppPath=[NSString stringWithFormat:@"%@/myApp.app",[fileMgr currentDirectoryPath] ];
    [[NSWorkspace sharedWorkspace] launchApplication:myAppPath];

但我无法弄清楚如何用参数做到这一点。在Cocoa/ Objective-C Shell Command Line ExecutionLaunching an Mac App with Objective-C/Cocoa之后,我尝试了:

    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *path=[NSString stringWithFormat:@"%@/myApp.app",[fileMgr currentDirectoryPath]];
    NSArray *args = [NSArray arrayWithObjects:@"arg1",@"arg2", nil];
    [[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

我收到错误:

*** NSTask: Task create for path '/path/to/app/myApp.app' failed: 22, "Invalid argument".  Terminating temporary process.

我确切地说我需要使用NSTask为waitUntilExit函数启动它。实际上,我需要启动其他应用程序的应用程序等到启动的应用程序退出。 谢谢!

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。事实上,它不是:

NSString *path=[NSString stringWithFormat:@"%@/myApp.app",[fileMgr currentDirectoryPath]];

但是:

NSString *path=[NSString stringWithFormat:@"%@/myApp.app/Contents/MacOS/myApp",[fileMgr currentDirectoryPath]];

所以最终的代码是:

NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *path=[NSString stringWithFormat:@"%@/myApp.app/Contents/MacOS/myApp",[fileMgr currentDirectoryPath]];
NSArray *args = [NSArray arrayWithObjects:@"arg1",@"arg2", nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];