views:

201

answers:

1

I notice that this method is provided in UIViewController .m files, but is commented out:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

I had been leaving that method commented out, or even deleting it. But then I looked at this line inside the method:

if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])

I assume that if it were truly important for self to be set equal to super, then Apple would not have the method be commented out by default. On the other hand, if I do need to do some customization in that method, why do I need to set self = super? What's the best practice, and why?

+1  A: 

What you are seeing with the calls to [super ...] is a nested initialization, where the derived class first calls its parent class to initialize before it continues. This is a common pattern in Cocoa as well as some other languages.

So this initWithNibName:bundle: method will be called if you are initializing the view controller with a matching nib (xib). Unless your derived view controller needs to do some special step during initialization then you don't actually need to define this method to override the parent's class implementation -- the existing implementation in UIViewController will be used. Initialization code is usually better off in viewDidLoad if you can manage it.

Since it's commented-out code, you can delete it without worrying very much about it.

Shaggy Frog
Great explanation, thanks. I notice that initWithNibName:bundle: fires before viewDidLoad, but I have never yet seen a view come to the screen before everything I put in viewDidLoad had been performed. So I will just delete the commented-out initwithNibName:bundle: methods.
Scott Pendleton