NSTask without worrying about the output buffer

February 18, 2011 by · 1 Comment 

Some times you might want to run NSTask without setting up a delegate for when data becomes available or to notify once the task has terminated because it in a procedural part of your application.

Here is a quick example using system_profiler and Applications…

NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:@"/usr/sbin/system_profiler"];
[task setArguments:[NSArray arrayWithObjects:@"SPApplicationsDataType",nil]];

NSPipe *l_Pipe = [NSPipe pipe];
NSFileHandle *readHandle = [l_Pipe fileHandleForReading];

[task setStandardOutput:l_Pipe];
[task setStandardError:l_Pipe];
[task launch];

NSMutableData *data = [[NSMutableData alloc] init];
NSData *readData;
while ((readData = [readHandle availableData]) && [readData length]) {
    [data appendData: readData];
}
// We now have our full results in a NSString
NSString *spStringData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[spStringData release];
[data release];
[task release];