views:

32

answers:

1

I know how to send data to the task:

NSData *charlieSendData = [[charlieImputText stringValue] dataUsingEncoding:NSUTF8StringEncoding];

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

But how do I get what the task responds with??

Elijah

+3  A: 

Give an NSPipe or an NSFileHandle as the task's standardOutput, and read from that.

NSTask * list = [[NSTask alloc] init];
[list setLaunchPath:@"/bin/ls"];
[list setCurrentDirectoryPath:@"/"];

NSPipe * out = [NSPipe pipe];
[list setStandardOutput:out];

[list launch];
[list waitUntilExit];
[list release];

NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"output: %@", stringRead);

Note that if you use a pipe, you have to worry about the pipe filling up. If you provide an NSFileHandle instead, the task can output all it wants without you having to worry about losing any, but you also get the overhead of having to write the data out to disk.

Dave DeLong
I already do that. [task standardOutput] - If I just call this, will it give the output?
Elijah W.
@Elijah by default, no. If you want the output, you have to provide a pipe or filehandle before launching the task, and then start reading from the filehandle (or `[pipe fileHandleForReading]`) in order to get the data back. (And it will give you `NSData` objects, not strings or anything)
Dave DeLong
Can you show an example?
Elijah W.
@Elijah edited answer.
Dave DeLong
Thanks! :D .....
Elijah W.