Note that there are some explanatory texts on larger screens.

plurals
  1. POOrder of UIViewController initialization and loading
    text
    copied!<p>I'm fairly new to UI programming on the Mac and iPhone, and I've run across something that somewhat puzzles me.</p> <p>A UIViewController has 3 methods that involve the initialization of it and its view:</p> <ol> <li>init (and init-like methods)</li> <li>loadView</li> <li>viewDidLoad (delegate method)</li> </ol> <p>I'd expect these to occur in the order above. First UIViewController is alloc'ed by some other object, then init is immediately called (or some other init method, like initWithStyle).</p> <p>Only once the object is initialized would I expect it to call its own loadView function, after which the view, once loaded, calls the viewDidLoad delegate method.</p> <p>This doesn't happen, for instance:</p> <pre><code>@implementation UIViewControllerSubclass - (id)init { NSLog(@"0"); if (self = [super init]) { NSLog(@"1"); } return self; } - (void)loadView { [super loadView]; NSLog(@"2"); } - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"3"); } @end </code></pre> <p>Produces the console output:</p> <pre><code>0 2 3 1 </code></pre> <p>The loadView and viewDidLoad methods, therefore, cannot make delegate calls, as the delegate is usually set after the call to [super init], which (as shown above) is called <em>after</em> loadView and viewDidLoad have run:</p> <pre><code>UIViewControllerSubClass *someViewController = [[UIViewControllerSubclass alloc] init]; [viewController setDelegate:self]; </code></pre> <p>If I want to run code that sets up the ViewController in some way, notifying the delegate as it goes, should the code reside in the init method? Isn't the reason for loadView existing to allow such code to be run at the appropriate moment?</p> <p>It looks to me like I'll have to create a new initWithDelegate method which sets the delegate ivar <em>before</em> calling [super init], is this right, or am I going about this the wrong way?</p> <p>Thanks in advance :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload