ios app startup

Thu, Jan 27, 2011

I’d thought I’d write down what goes on when you tap an App icon on the iPhone as it’s quite an interesting collection of bits ‘n bobs and shows how the code ties up with Interface Builder and nib files and the like. This is based on a new View Based Application in XCode, called HelloWorld, so start up XCode and create one. You can then follow along. In the nib files, where something is in quotes, i.e. “File’s Owner”, I’m referring to objects in Interface Builder and not application classes:

All the app does is display the text “Hello World!” in the middle of the screen, so I can concentrate on the startup without code clutter.

The ball starts rolling when the user fancies a bit of Hello World inspiration and taps the App icon. This causes the App’s main function to be called by iOS, which is in main.m:

The important bit here is UIApplicationMain, which is the Sherlock Holmes of iOS. It’s job is to wire everything up, so the first thing it does is look in HelloWorld-Info.plist, where it finds the App’s NIB file:

It then loads up MainWindow.xib and looks at “File’s Owner”, sees it is an instance of UIApplication with a delegate pointing to “HelloWorld App Delegate”. So It follows this and looks at “HelloWorld App Delegate”, sees it is an instance of HelloWorldAppDelegate, with its viewController pointing to “HelloWorld View Controller” and its window pointing to “Window”. So it’s found out which class to instantiate for the app delegate, HelloWorldAppDelegate.

UIApplication continues sleuthing with its NIBifying glass and looks at “HelloWorld View Controller” and sees it is an instance of HelloWorldViewController. So now it’s found the App’s view controller too, HelloWorldViewController. To close the case and exclaim “elementary, my dear Watson”, it looks at “Window” and sees it is an instance of UIWindow. So now it has all the class information it needs to proceed.

UIApplication now instantiates HelloWorldAppDelegate, UIWindow and HelloWorldViewController in that order but there’s still one piece of the jigsaw missing. The App’s view. Back to to MainWindow.xib goes UIApplication, to find the “Nib Name” setting of HelloWorldViewController, which points to HelloWorldViewController.xib. UIApplication then looks in this nib file “File’s Owner”, sees it’s HelloWorldViewController with its view member pointing to UIView, which is the App’s view, where the inspirational message for the user will be displayed.

Now that UIApplication, has all the pieces it calls HelloWorldAppDelegate::didFinishLaunchingWithOptions, where the app delegate adds the view to the main window. It knows about the view and main window as they are auto wired from MainWindow.xib by UIApplication. A bit of iOS dependency injection if you like.

To complete the process, HelloWorldViewController::viewDidLoad displays the text “Hello World!” and the user is happy!

comments powered by Disqus