views:

257

answers:

1

Clarification question as a follow up to:

http://stackoverflow.com/questions/2261972/what-exactly-must-i-do-in-viewdidunload http://stackoverflow.com/questions/1158788/when-should-i-release-objects-in-voidviewdidunload-rather-than-in-dealloc

So let's say there's a low memory error, and the view is hidden, and viewDidUnload is called. We do the release and nil dance. Later the entire view stack is not needed, so dealloc is called. Since I already have the release and nil stuff in viewDidUnload, I don't have it in dealloc. Perfect.

But if there's no low memory error, viewDidUnload is never called. dealloc is called and since I don't have the release and nil stuff, there's a memory leak.

In other words, will dealloc ever be called without viewDidUnload being called first?

And the practical follow up to that is, if I alloc and set something in viewDidLoad, and I release it and set to nil in viewDidUnload, do I leave it out of dealloc, or do I do a defensive nil check in dealloc and release/nil it if it's not nil?

+3  A: 

Release it in both. You don't need to check for nil. Release on a nil does nothing.

However in viewDidUnload don't release ivars that you can't easily recreate in viewDidLoad, in case the view becomes loaded again.

Normally (no memory warnings) viewDidUnload doesn't gets called, only dealloc is called.

progrmr
For good hygiene, should a nil set be done in dealloc?
entaroadun
To be safe yes, but I can only think of a few cases where it matters. I like using the setter to set it to nil, since it releases it and sets it to nil in one line (ie: self.ivar=nil;)
progrmr
There's really no reason to set ivars to `nil` in `dealloc`. Also, it's against Apple's recommendations to use setters in `dealloc` (i.e. `self.ivar = nil`), since there could potentially be a problem using setters in a partially deallocated object. It's probably not a problem to use setters, but to be 100% safe, you can use `[ivar release]` instead.
eman
@eman: good to know, thanks.
progrmr