【问题标题】:Launch command line in Objective C在 Objective C 中启动命令行
【发布时间】:2014-09-25 10:53:10
【问题描述】:

我想在 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 函数启动它。事实上,我需要启动另一个应用程序的应用程序等到启动的应用程序退出。 谢谢!

【问题讨论】:

  • 你可以使用 system(Const char *command) API 来实现。做一些研究。

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


【解决方案1】:

我找到了解决方案。其实不是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-13
    • 2011-07-06
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2021-03-24
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多