Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initWithNibName VS NSBundle's loadNibNamed

I've noticed that there are two different ways to load nib/xib files:

  1. via the UIView's initWithNibName:bundle: method
  2. NSBundle's loadNibNamed:owner:options: method.

Can someone explain the differences between these two and when it is more appropriate to use one over the other and in what circumstances?

For instance, if I'm loading a custom table section header view from a nib file in the tableView:viewForHeaderInSection: method, which one would I use?

Or, if I were loading a custom table view cell from a nib file, which one would I use?

like image 946
tbehunin Avatar asked Nov 09 '09 21:11

tbehunin


2 Answers

NSBundle’s methods are the generic API to use for unarchiving NIBs. They do the actual work (together with NSNib).

UIViewController’s initWithNibName:bundle: on the other hand is a way to initialize a view controller which (might) load its view from a nib. The method does not itself load the nib but just takes note of the name. The controller loads the nib lazily when the view is requested.

I’m not aware of any nib loading in UIView.

like image 167
Nikolai Ruhe Avatar answered Nov 06 '22 15:11

Nikolai Ruhe


If your header's view controller contains IBOutlets to any fields in the nib file it will be better to load the nib file instead of calling initWithNib. In the view controller of the header file modify the initiation statement as the following .The default statement is commented out.
By doing so you will be able to access the fields in the nib file using the IBoutlets.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    //self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    // Custom initialization.
    if ([[NSBundle mainBundle] loadNibNamed:@"NibFile" owner:self options:nil]) {

    }

    return self;
}
like image 10
prajul Avatar answered Nov 06 '22 14:11

prajul