Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a view from NIB, IBOutletCollection is nil even though other IBOutlet's are working fine

I laid out a view in a NIB file, then added my UIView subclass as the file owner.

The subclass looks like this:

@property (nonatomic, weak) IBOutlet UILabel *categoryLabel;
@property (nonatomic, weak) IBOutletCollection(UIImageView) NSArray *images;

The properties are weak because of this: https://stackoverflow.com/a/7729141/1016515

Then I wired up the label and the UIImageViews in the nib, from the view to the file owner.

Then, in the awakeFromNib part of the subclass, I did this:

[[NSBundle mainBundle] loadNibNamed:@"CategoryButton" owner:self options:nil];
NSLog(@"label: %@",self.categoryLabel);
NSLog(@"images: %@",self.images);

I expected to see the addresses of the categoryLabel and the images. Instead I found that the category label was fine and the images are nil.

This is quite puzzling, because the declarations for images and categoryLabel are identical. Why does one work and the other fail?

like image 355
divergio Avatar asked May 03 '13 08:05

divergio


1 Answers

I'm putting this up because I didn't find the question anywhere, but it seems like a pretty easy mistake to make if you're used to working with IBOutlets but not IBOutletCollections.

I made the properties weak because that's what I usually do for IBOutlets for the reasons discussed in another question.

What I neglected to realize is that the IBOutletCollection is an instance variable of the class, not just an arbitrary reference into the view hierarchy. Therefore, if it is a weak property the NSArray * will immediately be released because the view hierarchy isn't retaining it as it does for other IBOutlet properties.

The fix is simple, make the property strong:

@property (nonatomic, strong) IBOutletCollection(UIImageView) NSArray *images;

Update: According to this answer, almost all IBOutlets should be strong, unless they must be weak to avoid a retain cycle. This is new, and most documentation still says outlets should be weak.

like image 192
divergio Avatar answered Sep 28 '22 12:09

divergio