Could someone please explain how control of execution flows in an iOS application? I know that UIApplicationMain is called first from main. Then what? What is the relationship between my defined methods and main? Is it all event-driven or can there be some structured sequence?
I don't mean to be so vague, I just need to know where to start. Perhaps I'm looking at this in the wrong way.
For example, in C++ I would do something like:
#include "myMethods.h"
int main (int argc, char * const argv[]) {
Method1(); // Initialization
Method2(); // Opening views and options
Method3(); // Meat of the program
return 0;
}
Thanks in advance.
So, as you mentioned, the main()
function in main.m
is the starting point, which then calls UIApplicationMain()
. If you check the docs, you'll see that UIApplicationMain
takes four arguments:
The first two of those are just the argument count and variable list passed from main()
. But the third and fourth arguments are pointers to NSStrings. The third argument specifies which class should be UIApplication
. Unless you intend on subclassing UIApplication
, you specify nil
for the third argument. The fourth argument specifies which class should be UIApplication's delegate class, which will respond to anything specified in the UIApplicationDelegate
Protocol. You don't have to muck with this directly, as it's included in all of the Xcode templates:
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
Don't let the NSStringFromClass([AppDelegate class]))
bit throw you. That's just a fancy way of specifying the fourth argument so that the right delegate gets called should you later change the name of AppDelegate.m
.
UIApplication
starts the main event loop and calls -application:didFinishLaunchingWithOptions:
, one of the methods its delegate has to handle. Take a look at AppDelegate.m
, and you'll find some template code for this method. This is where you can start customizing, creating things that need to be in place before the UIWindow
and other instances of UIView
get created:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
So, now the application window and root view controller are defined, and the app is off and running.
All of this, and quite a bit more, is excellently explained here: http://oleb.net/blog/2012/02/app-launch-sequence-ios-revisited/