Thanks
Thanks

Reputation: 40329

Why is my initWithNib method not called when the view controller is loaded?

I have an class that inherits from UIViewController. There, I want to make some ivar initialization like this:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle { // Load the view nib
    NSLog(@"Hello Earth!");
    if (self = [super initWithNibName:nibName bundle:nibBundle]) {
        self.visibleIndex = 0;
        NSLog(@"Hello Planet!");
    }
    return self;
}

For some reason I do see the contents that were loaded from the nib. But for another reason this initializer will never be called. I never get the log messages. What's wrong with that? I have a nib for sure, so actually this would have to be called, right?

Upvotes: 2

Views: 3631

Answers (2)

DonnaLea
DonnaLea

Reputation: 8653

I think you are thinking of viewLoaded, not initWithNibName. viewLoaded is what's called if you want to setup a view programmatically. initWithNibName is called if you are loading with a nib.... hence the name? But the setting up of the view shouldn't be done until viewDidLoad, but other initialisation stuff should be done in initWithNibName, for instance, setting up any arrays or other variables.

Upvotes: 0

Gareth Davis
Gareth Davis

Reputation: 28059

This method isn't used if your UIViewController is being created by a nib. You need to override viewDidLoad:

-(void) viewDidLoad {
    [super viewDidLoad];
    NSLog(@"Hello Planet");
}

initWithNibName is only used if you are actually instantiating the controller by code.

Upvotes: 5

Related Questions