Tasks are launched in a separate process from your code, i.e. asynchronously. They probably havenβt finished yet (maybe they havenβt even started!) By the time of transition to readDataToEndOfFile two lines later.
If you are already in the background thread, you can poll their status: while( ![task isRunning]){ , or if you are in the main thread, I would suggest using GCD to put this in the queue and there is a poll.
Actually, it is better to use notifications:
[task3 launch]; [[NSNotificationCenter defaultCenter] addObserverForName:NSTaskDidTerminateNotification object:task3 queue:nil usingBlock:^{ NSData * data = [file readDataToEndOfFile]; NSString * string; string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog(@"Result: %@", string); }];
See TN2050: adherence to process time without polling Each NSTask sends an NSTaskDidTerminateNotification when it completes (you should ideally check its return code, and not consider it successful). You can create a block that will run when task3 sends this notification.
Josh caswell
source share