Retain count of UILabel


#1

referring to page 144, 145

I don’t have a specific question, but this section is breaking my understanding of who is responsible for releasing objects.

If I understand the discussion on these pages, my view controller retains timeLabel because it is a IBOutlet that is connected in the xib file. This happens when the view loads because my init method used initWithNibName. Therefore viewController should release timeLabel when told that its view was unloaded.

I find this confusing since I have no code with alloc, retain, copy. Why am I (objective c code for CurrentTimeViewController) responsible for release?
The retain was done behind the scenes, based on the xib file, so why isn’t there corresponding code to release it when it unloads, also behind the scenes? Based on this discussion, it seems like every time I connect a IBOutlet in the interface builder, I should add code in viewDidUnload to release it.
Is this correct?

Is there a better way to manage this?

Thanks
K


#2

Yes, this is correct. The XIB loading process sends the message setValue:forKey: to the view controller, where the value is the label and the key is timeLabel. This is the same as the following:

[incomingTimeLabel retain];
[timeLabel release];
timeLabel = incomingTimeLabel;

The confusion here is that this method is implemented in a superclass of your view controller. So even though you didn’t write the code to do the retain, this object still does the retain.

In iOS 5.0 and ARC, you can declare outlets as “weak” to get the same effect without writing the unloading code.