Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C : loadNibNamed method: how does it work?

I would know how loadNibNamed of NSBundle class works; In some document I find something like

[[NSBundle mainBundle] loadNibNamed:@"mynib" owner:self options:NULL];

without return value; just called inside a method (e.g. cellForRowAtIndexPath if I want to customize my cell). In other documents I find:

NSArray* vett=[[NSBundle mainBundle] loadNibNamed:@"mynib" owner:self options:NULL];

In this case, for example, in cellForRowAtIndexPath, I could

 return [vett lastObject];

or something like this. The latter method seems to me clear; I load the nib in a vector and then I use the vector elements. The problem is understanding what exactly do the first:

[[NSBundle mainBundle] loadNibNamed:@"mynib" owner:self options:NULL];

no return value, no cell reference...where are the objects of my nib? how are they handled? I don't understand how it works

like image 271
volperossa Avatar asked Sep 05 '15 00:09

volperossa


2 Answers

For example, you have a subclass UIView with custom nib @"CustomView"

You can load it:

    NSArray * arr =[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
    CustomView * customView = [arr firstObject];
like image 176
tuledev Avatar answered Nov 16 '22 10:11

tuledev


This method returns an array of the objects in the nib. If you want to instantiate a custom view for example you will want to use the return value in the way anthu describes.

NSArray * arr =[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil];
CustomView * customView = [arr firstObject];

If however you want to use the xib to configure the file's owner (note that you can pass in an owner to this method), you may not be interested in the array that is returned. E.g. If the xib connects the file's owner's IBActions and IBOutlets to elements in the xib.

[[NSBundle mainBundle] loadNibNamed:@"mynib" owner:self options:nil];

You may also combine both approaches.

like image 27
johnpatrickmorgan Avatar answered Nov 16 '22 09:11

johnpatrickmorgan