如何在 Cocoa 应用程序中包含和调用可执行文件?

How to include and call an executable in a Cocoa app?

我可以从 Cocoa 应用程序中的已知本地目录运行可执行文件,如下所示:

// Run the server.

NSTask *task = [[NSTask alloc] init];
NSPipe *pipe = [NSPipe pipe];
NSString* scriptPath = @"/Users/example/Server/runServerExecutable.sh";
[task setLaunchPath: @"/bin/sh"];
[task setArguments: [NSArray arrayWithObjects: scriptPath, nil]];
[task setStandardOutput: pipe];
[task launch];

谁能帮我解答这些问题?

非常感谢!

将 script/text 文件拖放到您的 xcode 项目 -> 项目导航器中,这样它就会添加到您的项目中。构建项目。打开Bundle,在Resources目录下可以看到添加的文件。

现在,下面给出的代码将帮助您从资源中获取文件。为了举例,我添加了一个名为 "OpenSafari.sh"

的脚本
NSTask *temp = [[NSTask alloc] init];
[temp setLaunchPath:@"/bin/sh"];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"OpenSafari" ofType:@"sh"];
NSArray *tempargs = [NSArray arrayWithObjects:filePath,nil];
[temp setArguments:tempargs];

NSPipe *temppipe = [NSPipe pipe];
[temp setStandardOutput:temppipe];
NSPipe *errorPipe = [NSPipe pipe];
[temp setStandardError:errorPipe];

[temp launch];

NSData *data = [[temppipe fileHandleForReading] readDataToEndOfFile];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSData *dataErr = [[errorPipe fileHandleForReading] readDataToEndOfFile];
NSString *resultErr = [[NSString alloc] initWithData:dataErr encoding:NSUTF8StringEncoding];

希望对您有所帮助!