views:

168

answers:

3

I am using @property(nonatomic, retain) for my IBOutlets for an iPhone application. However, I'm not sure how to make sure I'm managing memory with them properly. The IBOutlets are all set up in Interface Builder, so I'm never calling alloc manually. This means that I'm not sure when and if to deallocate them or when to set them to point to nil.

What are the best practices ensuring that no memory is leaked once the view unloads?

+2  A: 

If you use @properties for yourIBOutlets and make the connections in IB then your controller is essentially retaining the IB objedcts with the property and is it therefore responsible for releasing them when it's done with them.

When are you done with them?

In every case you should be setting your properties self.propertyname = nil in your viewDidUnload method and again in dealloc of each viewController.

It's quite straight forward, IB manages everything else.

Jessedc
I am pretty sure this is wrong. If you nullify your outlets in `-viewDidUnload`, you run into problems when you need to load your view again. This happens when you view got unloaded during a low memory warning, and it needs to be shown again.
Johan Kool
Johan: you are mistaken. You generally should set outlets to nil in `-viewDidUnload` precisely to make the memory warnings work. If you don't, the view controller retains the outlets (which are often subviews of the view being unloaded and can't be freed). If the view needs to be shown again, the view controller will reload the NIB and reconnect the outlets. Of course, you should not release outlets that you need to remain alive even when the view gets unloaded (i.e., the view controller is off screen).
Ole Begemann
A: 

By default, the semantics of @property is retain, meaning that when the view controller loads the nib and connects IBOutlets, they get retaind by the @synthesized setter. Follow the standard rules of Cocoa memory managment: you must release these properties eventually or you will leak memory. dealloc is probably a good place to do this. On the iphone you can do this via self.outletProperty = nil. On OS X (when you're not using GC), the rules are the same, except you can use [self->outletProperty release] explicitly, bypassing the @synthesized setter.

Barry Wark
A: 

You should do it like this....

[yourOutletVar release];
yourOutletVar = nil;

Please don't forget to set the IBOutlets to nil finally, because it is necessary to get rid of dangling pointers issue.

Madhup