Search code examples
xcodemacoscocoaosx-snow-leopardosx-lion

Accepting arguments with Cocoa and running system commands


I am new to Cocoa and Xcode, but I really do want to learn. The problem is that I spend a lot of my time doing work in scripting languages like PHP, perl, python, and shell scripting, and while Cocoa is a lot more powerful than running a shell script in Terminal on OS X, it is also a bit harder to get into.

I have a hypothesis though: If I can start using Cocoa and Xcode to actually do some things then I'll get more comfortable with it and gradually start to unlock more and more of it's potential.

That's where I hope StackOverflow comes in. See, I'm used to writing scripts that take paramaters (mostly file names) as inputs, and act on them - either dispatching other programs or reading and writing to the text-based contents. So with that in mind, How can I write a simple Cocoa application that will accept input, save that input to a file, and launch a system command?

Desired input:

open -a MyApp.app --args "hello world"

Desired output:

  • File /tmp/test.txt is created and now contains text hello world
  • The php version is checked by running /usr/bin/php -v and the output is then appended to /tmp/test.txt (just wanted to call some system command)

I know this sort of thing is very easy to do with just 1-2 lines of something like bash scripting, but I'd really like to see if I could make this happen in a Cocoa app. I apologize in advance because I realize this is very much a noob question - just trying to get started in a way that feels familiar.


Solution

  • If you want to process command-line arguments and have a GUI, you'll definitely want to look at NSProcessInfo. Among other things, it has a method called arguments that returns the command-line args as an NSArray.

    It can also give you an NSDictionary of environment variables, which can also be really useful, from the environment method.

    Edit: I forgot to mention, if you want to save the contents of a string to file, NSString already has a method for that! Look at the docs for writeToFile:atomically:encoding:error:.