Cocoa Objective-C shell script from application?

2019-03-14 08:41发布

I have an application that I'm creating and would like to run a shell scripts from within it. One of the scripts creates a .plist file, and the other does a patch on a binary file. The reason why want to do this with a shell script is because I know that it works for the two things that I need it for. I'm sure there's a way to do it with Objective-C/Cocoa although I don't know how, so any recommendations on how to accomplish this would be greatly appreciated

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-14 09:19

You'll need to use NSTask. NSTask is a system for running any Terminal command. Here's how you could use it to execute a shell script:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/script/sh"];
[task setArguments:[NSArray arrayWithObjects:@"yourScript.sh", nil]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];

[task launch];
[task release];

That would run the command /path/to/script/sh yourScript.sh. If you need any arguments for your script, you can add them to the array of arguments. The standard output will redirect all output to a pipe object, which you can hook into if you want to output to a file. The reason we need to use another NSPipe for input is to make NSLog work right instead of logging to the script.

If you want more info on how NSTask works, see this answer.

查看更多
Evening l夕情丶
3楼-- · 2019-03-14 09:24

The easiest way I know is NSTask. It's just like a terminal command from where you can call your bash script.

查看更多
登录 后发表回答