Ios – iPhone SDK: what is the difference between loadView and viewDidLoad

iosiphoneobjective cuiview

When working with views and view controllers in an iPhone app, can anyone explain the difference between loadView and viewDidLoad?

My personal context, is that I build all my views from code, I do not and will not use Interface Builder, should that make any difference.

I've found that often when I add init code to loadView, I end up with an infinite stack trace, so I typically do all my child-view building in viewDidLoad…but it's really unclear to me when each gets executed, and what is the more appropriate place to put init code. What would be perfect, is a simple diagram of the initialization calls.

Thanks!

Best Answer

I can guess what might be the problem here, because I've done it:

I've found that often when I add init code to loadView, I end up with an infinite stack trace

Don't read self.view in -loadView. Only set it, don't get it.

The self.view property accessor calls -loadView if the view isn't currently loaded. There's your infinite recursion.

The usual way to build the view programmatically in -loadView, as demonstrated in Apple's pre-Interface-Builder examples, is more like this:

UIView *view = [[UIView alloc] init...];
...
[view addSubview:whatever];
[view addSubview:whatever2];
...
self.view = view;
[view release];

And I don't blame you for not using IB. I've stuck with this method for all of Instapaper and find myself much more comfortable with it than dealing with IB's complexities, interface quirks, and unexpected behind-the-scenes behavior.