开发者

Put `stdout` in an `NSTextView` while running the a command

I'm creating a Cocoa Application, which will need to run the rails command. This command generates an output, and streams it to stdout. I want to show this output to the user in an NSTextView (so basicly stream the stdout to the NSTextView). My application should not 'hang' when the command is running (e.g. the git command takes a long time to 开发者_如何学Cfinish uploading). I don't really care about how I should run the command, as long as I can set the working directory.

Using a Ruby framework for Cocoa is no option, as I also need to do this for non-ruby commands like git.

Can anyone help me? Thanks


You will need to use the NSTask class.

NSTask       * task;
NSPipe       * pipe;
NSFileHandle * fileHandle;

task       = [ [ NSTask alloc ] init ];
pipe       = [ NSPipe pipe ];
fileHandle = [ pipe fileHandleForReading ];

[ fileHandle readInBackgroundAndNotify ];
[ task setLaunchPath: @"/bin/ls" ];
[ task setStandardOutput: pipe ];
[ task setStandardError: pipe ];
[ task launch ];

You can then use the file handle to get stdout.
The working directory can be set with the setCurrentDirectoryPath method.
Arguments can be set with the setArguments method.


if you need to use the data during it es read use the approach with NSNotification which is described in this post on cocoabuilder.com.

Basically this sets up an NSPipe object, connects the stdout of the NSTask to the pipe and listens for NSFileHandleReadToEndOfFileCompletionNotification of the pipe to process the data which was pushed to the pipe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜