/ R. Matthew Emerson / blog

Command-line compiling of Cocoa code

May 30, 2007

I find that tools like Xcode are often too heavyweight when trying out little fragments of code. In these cases, it can be simpler to use the traditional Unix tools to edit, compile, and run tiny test programs. (Of course, it might be simpler for me because I’m used to the traditional Unix way.)

For instance, say that you have created a category on NSMutableArray that adds a method to reverse the contents of the array, and you’re ready to test it out.

You could create an Xcode project for this (you’d use the Foundation Tool template), but it’s also possible to use a Unix text editor (like emacs or vi) to create the file that contains your category, together with a simple main() function. (Here is an example file.)

There are basically two tricks to know. The first is that you need to create an autorelease pool before you call any methods, or else you’ll see warning messages about leaking objects. The other trick is how to compile the file, and that is simply

cc file.m -framework Foundation

Now, just run a.out. Debug, edit source, re-compile, repeat.