I have seen code (probably Apple's own sample code) written in such a way where it releases the ivar in dealloc and setting the property in viewDidUnload.
e.g.
- (void)viewDidUnload
{
self.navigationController = nil;
}
- (void)dealloc
{
[_navigationController release];
}
Why do them in two places? Also, why set nil in one and release in another. It seems that self.property = nil would just take care of everything since it would release and set the ivar to nil.
You're right: you can indeed do self.property = nil
everywhere, including dealloc. The only downside is that if the setter method does anything more complicated than just releasing the ivar, you might end up trying to access other fields that have already been released, etc.
As for why you also release the outlet in viewDidUnload
, that's a memory optimization. Since the stuff you release in viewDidUnload
are things that will be reinstantiated when the view is loaded again, releasing them there frees up memory in low-memory situations.
Apple recomments that you not call setters in the init and especially dealloc routines.
This is due to the fact that the object is only partially set up at this time, and setters could have observers attached to them, or could be overridden by subclasses, and otherwise have undesirable affects during dealloc, or could be confused during init with a partially configured object.
Hence, you normally use:
_navigationController = [[NavController alloc] init];
style code in your init routine,
[_navigationController release];
style code in your dealloc, and setters in other code where the object is known to be fully complete.
Some cases to consider:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With