Friday, May 15, 2009

Creating a NIB-free Cocoa Touch application in XCode

Do you program Cocoa Touch apps? Do you hate that all of the project templates expect you to be using interface builder? Me too! Here's how to get rid off all IB dependencies in your app!


Why would you want to do this?
Because programatically creating interfaces is considerably easier to deal with. (In my opinion anyway.)

How do you do it?
I'm glad you asked. It's a little bit of a hassle, BUT it's worth it.

So here we go.

1) Create a new project in XCode using the "Window Based Application" template (Title it whatever the heck you want. For the sake of this tutorial I'm calling it "NoNib")

2) Looking at all the contents of your new app you should see:
CoreGraphics.framework
Foundation.framework
Info.plist
main.m
MainWindow.xib
NoNib.app
NoNib_Prefix.pch
NoNibAppDelegate.h
NoNibAppDelegate.m
UIKit.framework

Go ahead and delete MainWindow.xib (the NIB) and send it to the trash. You don't need it.

3) Open Info.plist
Select the line with key "Main nib file base name" and delete it

4) Open main.m
Find the line "int retVal = UIApplicationMain(argc, argv, nil, nil);" and replace the second line with the name of your AppDelegate as a string (example "int retVal = UIApplicationMain(argc, argv, nil, @"NoNibAppDelegate");")

5) Open your AppDelegate.h file and remove the line "@property (nonatomic, retain) IBOutlet UIWindow *window;"

6) Open your AppDelegate.m file
Remove the line "@synthesize window;"
Then, within - (void)applicationDidFinishLaunching:(UIApplication *)application before the line that says "[window makeKeyAndVisible];" add this line "window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];"

7) Build and Go
If it doesn't build without error, you most likely missed something in the above steps. Otherwise it should launch in the simulator as a completely empty app with a black background. CONGRATULATIONS! You can now start building Views and View Controllers without any of those icky interface builder remnants dragging you down.

2 comments:

Unknown said...

nib free! I would LOVE to be able to create labels, views, etc. without using Interface Builder, but I simply don't know how to do that. Can you direct me to a reference that tells me how. Just a simple example of creating a label with a given size and background would be GREAT.

OgreSwamp said...

Hi Andrew!
Thanks for the article.

Just one thing, if you delete window propety then you should add UIWindow *window; to the .h file. At least I wasn't able to compile source without that. window isn't defined in superclass, so you need to define it in the .h