Yesterday I was working on some code that made use of NSTask and ran into a tiny, yet annoying, issue. Essentially the code block I was working on would search a directory on the machine and return an array of paths to items which matched the results of the call to the ‘find’ tool. The only problem I found is that when I called
[task setStandardOutput: pipe];
The results from the ‘find’ command were dumped in the console.app and not in the debugger. After a little investigation, I realized I simply was just missing this call:
[task setStandardInput:[NSPipe pipe]];
After making this adjustment, NSLog was now appearing back in Xcode’s debugger/console. Yay!
Here it is in action:
#import "FileFindAppDelegate.h"
@implementation FileFindAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self findFiles];
}
-(void)findFiles
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:@"-c", @"/usr/bin/find /Users/jeffsoto/Desktop/Files -name *title*", nil];
[task setArguments: arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
[task setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSArray *array = [[NSArray alloc] initWithArray:[string componentsSeparatedByString:@"\n"]];
NSLog(@"Found %i matching files", [array count]-1);
int i;
for(i=0; i < [array count]-1; i++)
{
NSLog(@"Found this path %@", [array objectAtIndex:i]);
}
}
[task release];
[string release];
[array release];
@end