tags:

views:

16

answers:

1

I used to declare IBOutlets for iPhone like so,

IBOutlet UILabel *myLabel

I just found out that the correct way to declare them is like,

UILabel *myLabel;
@property(nonatomic,retain) IBOutlet UILabel *myLabel; 

But with the second and correct way do you have to release each IBOutlet in the -(void)dealloc method to avoid memory leaks?

+3  A: 

In short, they should be deallocated either way. In the 2nd approach, all you're doing is creating a getter/setter pair, which doesn't handle deallocation at the proper time. It has some logic that knows when to properly deallocate when an object is replaced, but it can't do the final cleanup there, because the setter still allocates a new object that way.

Look at it this way: You have to deallocate objects that you specifically allocated. If your outlet, through the course of your code, or by virtue of instantiated data from a NIB file was assigned an object, at some point you're responsible for cleaning up after it (unless it came from an autorelease convenience method).

Joost Schuur
thanks! very helpful
Glad I could help. I want to correct one small thing in my answer above: When the setter is used to replace (or just set) a value (self.myLabel = newLabel), it doesn't actually allocate a new object like I said. It does increase the retain could of newLabel (because of the 'retain' part in your property declaration), so you have to perform a release in dealloc.
Joost Schuur