initWithNibName:bundle and encapsulation

Untitled Blog Post Name

When you initialize a new View Controller you might use some code like this:

    MyCustomViewController *myCustomViewController = [[MyCustomViewController alloc] 

        initWithNibName:@”MyCustomViewController” bundle:nil];

and there’s plenty of code about (including from Apple) that use this.
However, it isn’t great.

For starters it breaks encapsulation by exposing the name of the NIB file outside the View Controller.

Here’s a better way of doing this:

@implementation MyCustomViewController

    

// This is the designated initializer

– (id)init

{

    NSString *nibName = @”MyCustomViewController”;

    NSBundle *bundle = nil;

    self = [super initWithNibName:nibName bundle:bundle];

    if (self) {

        …

    }

    return self;

}

Now override the old designated initializer to use the new one instead:

– (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle

{

// Disregard parameters – nib name is an implementation detail

return [self init];

}

This excellent post goes into plenty of detail:

http://oleb.net/blog/2012/01/initWithNibName-bundle-breaks-encapsulation/

Leave a Reply

Your email address will not be published. Required fields are marked *