7

Clarification question as a follow up to:

What exactly must I do in viewDidUnload? When should I release objects in -(void)viewDidUnload 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?

Community
  • 1
  • 1
jennykwan
  • 2,631
  • 1
  • 22
  • 33
  • 3
    You know you can send nil a release message no problem, right? nil simply ignores all messages sent to it and returns nil as it's value with no error. No need for defensive checks for nil like with NULL – Brandon Bodnar May 16 '10 at 15:52

1 Answers1

8

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
  • 75,956
  • 16
  • 112
  • 147
  • 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 May 16 '10 at 17:28
  • 6
    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. – shosti May 16 '10 at 20:16