Why do we need (id)initWithNibName?


#1

Hello;

I am following the ebook version on Quiz Application

My questions is that why do we need: (id)initWithNibName?
I can active the same result by initializing the arrays in the ViewdidLoad method.

[code]- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

if (self) {
    questions = [[NSMutableArray alloc] initWithObjects:
                 @"One", 
                 @"Two", 
                 @"Three",
                 nil];
    answers = [[NSMutableArray alloc] initWithObjects:@"1",@"2", @"3",nil];
    
}

}[/code]

So my question is: why do we need to use the init method when the following works perfectly fine? Unless I am missing something.

Thank you.

This is what I have:

[code]//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
//
// self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//
// if (self) {
// questions = [[NSMutableArray alloc] initWithObjects:
// @“One”,
// @“Two”,
// @“Three”,
// nil];
// answers = [[NSMutableArray alloc] initWithObjects:@“1”,@“2”, @“3”,nil];
//
//
// }
// return self;
//
//}

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    if (self) {
    questions = [[NSMutableArray alloc] initWithObjects:
    @“One”,
    @“Two”,
    @“Three”,
    nil];
    answers = [[NSMutableArray alloc] initWithObjects:@“1”,@“2”, @“3”,nil];

    }

}
[/code]


#2

initWithNibNamed:bundle: only gets called once when the view controller is created. viewDidLoad will possibly get called multiple times. Thus, your arrays and questions will be replaced. In this app, that isn’t a big issue since the data is constant, but with data that changes, it will be.

You should create all model objects in initWithNibNamed:bundle: and all view configurations should be done in viewDidLoad.


#3

Thank you Joe,
That make sense. Thank you for clarification.
Excellent book by the way.
My goal is to finish the book and join your class.

Thanks again.