NSTask and NSPipe example to comunicate with the command line objective-c

眉间皱痕 提交于 2020-01-01 06:39:32

问题


Can someone show a quick example on how to use NSTask and NSPipe in conjunction to do this:

Charlie AI - run through terminal to comunicate with the AI

I want to create a nice GUI for it using xcode and objective c. I want to have 2 NSTextFields for the charlie's response and user input. Then have a send button to send the user input to the command line, then get the charlie's response and post it in the NSTextField.

I can handle the GUI stuff (NSTextField, ect.) But I need help with the objective-c coding part.

Thanks!

Elijah


回答1:


Apple have some nice sample code that shows how to do most of that... http://developer.apple.com/mac/library/samplecode/Moriarity/

TaskWrapper.m contains all the clever stuff, but since you want to be able to send data to the task, you'll need to extend it a little, like so:

[task setStandardInput: [NSPipe pipe]];

To send input to the task, you can then do:

[[[task standardInput] fileHandleForWriting] writeData: ...];

To turn the NSTextField's value into data, you can do something like this:

NSData *data = [[inputTextField stringValue] dataUsingEncoding:NSUTF8StringEncoding];

...and to set the current working directory for your sub-task, use [NSTask setCurrentDirectoryPath:]

e.g.

[task setCurrentDirectoryPath:@"/blah/blah"];
[task setLaunchPath:@"/blah/blah/server.sh"];

.... (other setup code)

[task launch];



回答2:


There's also AMShellWrapper sample code which improves on moriarity.

http://www.harmless.de/cocoa-code.php



来源:https://stackoverflow.com/questions/3208696/nstask-and-nspipe-example-to-comunicate-with-the-command-line-objective-c

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