5

Can anyone explain why viewDidLoad does not get called when loadView is used? It's my understanding that viewDidLoad should still get called.

- (void)loadView
{
    CGRect currentFrame = [[UIScreen mainScreen] applicationFrame];

    UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(currentFrame.origin.x, currentFrame.origin.y, currentFrame.size.width, currentFrame.size.height)];
    myView.backgroundColor = [UIColor redColor];

    self.view = myView;
    [myView release];

    [super loadView];
}

- (void)viewDidLoad {

    //this never happens
    NSLog(@"VIEW DID LOAD!");
    [super viewDidLoad];
}
sol
  • 6,402
  • 13
  • 47
  • 57

3 Answers3

8

I've just found out that viewDidLoad won't be called if you call loadView manually in your application. If you call loadView manually you have to call viewDidLoad manually as well.

More over according to apple docs you shouldn't call [super loadView] as it will overwrite your view with a default UIView.

Piotr Czapla
  • 25,734
  • 24
  • 99
  • 122
  • 2
    Update: With recent versions of UIKit you can call `loadViewIfNeeded`, which does call `viewDidLoad` – wardw Sep 24 '17 at 14:43
3

You must have a warning here:

NSLog("VIEW DID LOAD!");

Instead, you should write like this (the @ sign is necessary):

NSLog(@"VIEW DID LOAD!");
Di Wu
  • 6,436
  • 3
  • 35
  • 51
  • ok, that was a typo. But the question is why that line never gets reached at all. – sol Jan 11 '11 at 01:16
  • 1) Have you try the "@" yet? Make sure you tried since it won't get you an Error, it'll only get you a Warning so you may just forget to add it back. 2) Have you seen the view you created in your loadView() actually appear on the screen? If not, chances are that the view was not created in the first place. – Di Wu Jan 11 '11 at 01:21
  • Yes, the view appears on screen. – sol Jan 11 '11 at 17:38
1

viewDidLoad will not get called when you create instance of ViewController. When you are pushing it to navigation controller or present it as model viewcontroller, then only the viewDidLoad get called. Until and unless you are presenting viewController, these delegate will not get called. And one more thing, if your viewcontroller presentation over, and still it remains in the stack or memory, then viewDidLoad method will not get called again because its already load the view. Then viewWillAppear and viewDidAppear delegates only get called when you present the same viewController.

Augustine P A
  • 5,008
  • 3
  • 35
  • 39