Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to release IBOutlets when using loadNibNamed: method?

I have a .xib file containing a UIView and 2 UILabel subviews linked to a class named Note with outlets assigned to each label appropriately, the definition for this class contains the following.

@interface Note : UIView {
    IBOutlet UILabel *time;
    IBOutlet UILabel *content;
}

I'm constructing this with the following code

NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"Note" owner:self options:nil];
note = [nibViews lastObject];
[self addSubview:note];

Now, in my Note class dealloc phase, I'm not releasing either time or content, but I'm wondering if I should?

- (void)dealloc {
    [super dealloc];
}

I'm assuming I don't because I'm not explicitly retaining these objects anywhere in my code, and I don't synthesize these into getter/setters. But I don't know enough about nib unarchiving to know whether I should be releasing these in my dealloc phase or not?

like image 496
seanalltogether Avatar asked Dec 19 '08 23:12

seanalltogether


2 Answers

You should release an IBOutlet even if you're not writing or synthesizing accessor methods. The NIB lifecycle documentation says that although unarchived objects are initially set to autorelease, the retain count on them is bumped up by an extra 1 when UIKit hooks up all the IBOutlet connection bindings. You therefore need to manually decrement via release when you're done.

It's not obvious that UIKit would be doing this so you might assume you can just leave the setter/getter methods off and trust that everything is autoreleased. But that's not the case.

Notice that Interface Builder templates explicitly release any IBOutlets, so any you add should be treated likewise.

like image 159
pioneer78 Avatar answered Sep 20 '22 07:09

pioneer78


This is correct for the iPhone; it would not be correct on the Mac, though.

However, you may want to rework this code. It isn't safe to assume that the view will be the last object loaded from the nib. I'd suggest instead that you either connect it to a "note" outlet in your view controller or scan the list for an object that's a subclass of Note. (If you're loading multiple Notes and you use the outlet option, just make sure you add one Note before loading another.)

like image 32
Becca Royal-Gordon Avatar answered Sep 19 '22 07:09

Becca Royal-Gordon