I've noticed that there are two different ways to load nib/xib files:
initWithNibName:bundle:
methodloadNibNamed: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?
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
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With