When should I initialize the view controller with initWithNibName?

When should I use init: and when should I use initWithNibName:bundle: when creating a view controller?

+48
initialization objective-c iphone uiviewcontroller
Feb 08 '10 at 18:57
source share
4 answers

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

You will often see this code:

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

I say this is not true. It places the implementation details in the calling program (NIB name and the fact that NIB is used). This violates 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 data back to the object and prevents accidental encapsulation violation of callers. Now, if you change the NIB name or go to the software design, you will fix it in one place (in the view controller), and not in every place where the view controller is used.

+136
Feb 08 '10 at 21:33
source share

Use initWithNibName: bundle: if you ... initialize with a nib file! This is the file that you created using Interface Builder.

If you are not using IB to build your views, you can simply use init .

+6
Feb 08 '10 at 19:03
source share

You can simply call init if xib has the same name as the view controller class. Encapsulation is not required. This saves typing but may not serve as clarity.

  NUDMainViewController *mainVC = [[NUDMainViewController alloc] init]; 
+2
Jun 24 '14 at 10:27
source share

using init when there is no nib / xib file, for example. The user interface is created by encoding

using initWithNibName if we have a share of nib / xib or one controller for more than 1 nib / xib

 if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil]; } else { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil]; } 

what I think..

0
Sep 02 '13 at 9:44 on
source share



All Articles