Reputation: 7822
I use to create my views programmatically and have started to switch using XIB files. I found this code:
-(id)init
{
self = [super initWithNibName:@"HelpViewController" bundle:nil];
if (self != nil) {
// further initialization needed
}
return self;
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
NSAssert(NO, @"Initialize with -init");
return nil;
}
It works but why? If I follow the logic, the initWithNibName returns nil and sets it to self. So, self is now nil and then you return self at the end of init. Well, that means you return self which is nil. Is that right?
Also, if I wanted to initialize a NSArray, where should I put it in that init function?
Thanks for the explanation.
Yko
Upvotes: 1
Views: 5519
Reputation: 71
It works because you are calling -initWithNibName:bundle: on super (most likely UIViewController), rather than on self (your subclass of UIViewController). If you were to call initWithNibName:bundle on self, then you would hit the assertion or return nil if you have disabled assertions. The superclass implementation of -initWithNibName:bundle: is not affected by your implementation and therefore continues to behave as it normally would.
Upvotes: 1
Reputation: 1220
Because the init method calls the self = [super initWithNibName...]. So You must call the init method to create the object. If you use initWithNibName it will fails
For Array you should initialize in init method
-(id)init
{
self = [super initWithNibName:@"HelpViewController" bundle:nil];
if (self != nil) {
// further initialization needed
myArray = [[NSMutableArray alloc] init];
}
return self;
}
Upvotes: 3
Reputation: 361
You're looking at two different initWithNibName functions.
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
NSAssert(NO, @"Initialize with -init");
return nil;
}
The above function is overriding the superclass version of initWithNibName. It raises an assertion informing the caller to use init.
self = [super initWithNibName:@"HelpViewController" bundle:nil];
The above line is calling the superclass version of initWithNibName, which returns a view controller.
If you wanted to initialize an array, you would initialize it where the "further initialization needed" comment is.
Upvotes: 1