Question

I've read solutions for doing this using NSTask: they all look very very long... So I managed to do the exact same thing using this code (which gets both standard output and standard error):

NSTask *task = [NSTask new];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:@[ @"-c", @"aCommand"]];
NSString *stringToRemove = [task description];
[task launch];
NSString *output = [[task description] stringByReplacingOccurrencesOfString:stringToRemove withString:@""];

Are there any drawbacks using this solution? Is there a shorter way to filter the output?

Was it helpful?

Solution

Are there any drawbacks using this solution? Is there a shorter way to filter the output?

Yes, many drawbacks. You are relying on an implementation detail that description will magically return the task's command line and output. That is not claimed by the documentation nor is description really acceptable to use beyond debugging/logging.

I.e. that code only works by convenience.

But that code isn't really working. If the command you were to run never exits or takes a while to run or produces a massive amount of output, then that code is likely to not actually grab any of the output at all or to spew truncated output.

There is a reason why the examples that use NSTask tend to be a bit lengthy. Managing I/O between processes is actually quite hard and there are a lot of different options that need to be taken into account.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top