When should I initialize a view controller using initWithNibName?

-initWithNibName:bundle: is the designated initializer for UIViewController. Something should eventually call it. That said, and despite Apple’s examples (which favor brevity over maintainability in many cases), it should never be called from outside the view controller itself.

You will often see code like this:

MYViewController *vc = [[MYViewController alloc] initWithNibName:@"Myview" bundle:nil];

I say this is incorrect. It puts implementation details (the name of the NIB and the fact that a NIB is even used) into the caller. That breaks encapsulation. The correct way to do this is:

MYViewController *vc = [[MYViewController alloc] init];

Then, in MYViewController:

- (instancetype)init
{
   self = [super initWithNibName:@"Myview" bundle:nil];
   if (self != nil)
   {
       // Further initialization if needed
   }
   return self;
}

- (instancetype)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
    NSAssert(NO, @"Initialize with -init");
    return nil;
}

This moves the key implementation details back into the object, and prevents callers from accidentally breaking encapsulation. Now if you change the name of the NIB, or move to programmatic construction, you fix it in one place (in the view controller) rather than in every place the view controller is used.

Leave a Comment