Objective C : loadNibNamed method: how does it work?
Asked Answered
D

2

7

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

Dido answered 5/9, 2015 at 0:8 Comment(1)
I can't say it any better than iOS documentation for that API or give you a better overview than this section on allocating a custom viewAbjure
G
4

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.

Gadid answered 5/9, 2015 at 9:34 Comment(0)
C
5

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];
Calv answered 5/9, 2015 at 1:44 Comment(0)
G
4

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.

Gadid answered 5/9, 2015 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.