NSTask 100

Jan 14, 2012 | Apple, Apps, Mac OS X, Objective-C, Programming, Tools

I’ll get right to the point here. Reinventing the wheel is bad. Period. End of sentence. If you have a requirement that can be met by an acceptably licensed open-source software project and you are not using that project, then you are likely adding unneeded complexity to you project; you are certainly adding development time and therefore cost to the project.

Recently, I have been spending a lot of time developing an internal Mac OS X application for a client. This is a large scale application that has a lot of very specific requirements; these requirements range for media conversions to data sorting. After spending a little time trying to create my own internal Objective-C classes for many of these functions, I started wishing that I could just call down to OS X’s underlying UNIX utilities.

Then I remember something that I had read in a Cocoa book almost a year ago: NSTask. I popped open Dash and got to reading the documentation on this awesome class. Basically, you can use NSTask to call down to a UNIX utility, pass it parameters as you would from the terminal, and deal with its output.

Let me show you an example of how this would work with one of my favorite GPL’d tools: LAME.

NSTask* lameTask = [[NSTask alloc] init];
[lameTask setLaunchPath@”PATH_TO_LAME”];
[lameTask setArguments:[NSArray arrayWithObjects:@”CRAPPY_AUDIO_FILE.wav”, @”NEW_AWESOMENESS.mp3”, nil]];
[lameTask launch];
<

That’s it. It really is that simple. Keep in mind that for this to work the user needs to have LAME installed on his box already for this to work and distributing GPL’d software with proprietary software can be legally jeopardizing, so read those licenses. Also, MP3 is an IP encumbered format and I am not suggesting that you should violate IP by using the above code; I am only using it as a fun and easy to understand example of using NSTask to call a UNIX tool/

I hope this helps somebody out, if you have any questions or comments, please let me know or comment below.

More from Mike:

About Me

Hi! I’m Mike! I’m a software engineer who codes at The Mad Botter INC. You might know me from Coder Radio or The Mike Dominick Show.  Drop me a line if you’re interested in having some custom mobile or web development done.

Follow Me

© 2024 Copyright Michael Dominick | All rights reserved