theiOSguy
theiOSguy

Reputation: 608

UIViewController designated initializer vs loadView method

I have my view controller class MyVC extending from UIViewController class. In the designated initializer I change the background color to GREEN as following

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view setBackgroundColor:[UIColor greenColor]];
    }
    return self;
}

I also have the loadView method that creates a new UIView object and changes its color to RED

- (void)loadView
{
    UIView* view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    [view setBackgroundColor:[UIColor redColor]];
    [self setView:view];
    [view release];
}

The designated initializer is called before loadView call. So I expect that my view color (which I set GREEN in designated initializer) should become RED (which I did in loadView). I see my color GREEN and if I comment that GREEN color line in designated initializer, then I see the RED color. So why is it not overriding the view properties in loadView method if it is called after initializer?

Upvotes: 1

Views: 1389

Answers (2)

Caleb
Caleb

Reputation: 124997

The purpose of -loadView is to, uh, load the view. It's called when you access the view controller's view property and the value of that property is nil. In this case, you're accessing self.view in your initializer, so that's when -loadView gets called. You set the view's background after that happens, so the view ends up with a green background.

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385500

Caleb has it almost right. When you access a view controller's view property, the view accessor method checks whether the view has been loaded yet. If not, it calls loadView, then viewDidLoad, then returns the view.

This line in your initializer accesses the view property:

    [self.view setBackgroundColor:[UIColor greenColor]];

So to return the view, the view accessor calls your loadView method. Your loadView method sets the view's background color to red. Then your initializer sets the background color to green.

If you sprinkle some NSLogs in your initializer and your loadView method, or if you put a breakpoint in your loadView method, you will see that loadView is called from view, which is called from initWithNibName:bundle:.

Upvotes: 9

Related Questions