views:

41

answers:

1

If you set a property to nil in viewDidUnload do you need to release it again in dealloc?

+2  A: 

No, but:

  • You don't need to check for that case. [nil release] is fine.
  • You can't count on viewDidUnload being called.

So just release as normal in -dealloc.

Of course, you must make sure that you actually released the previous object. You implicitly do this if you used the synthesized setter:

self.myProperty = nil;  // good
// or
[self setMyProperty:nil]; // also good

But setting the ivar to nil will leak:

self->myProperty = nil; // leaky as a sieve
// or 
myProperty = nil; // as useful as a screen door on a submarine

These are common errors.

Also note that setting properties to nil in -dealloc is a bad idea. As Kendall points out in the comments, you may unexpectedly invoke KVO behavior. There's a fuller discussion at http://stackoverflow.com/questions/3402234/properties-in-dealloc-release-then-set-to-nil-or-simply-release/3402247#3402247.

Seamus Campbell
can I do property = nil in viewDidUnload and [property release] in dealloc? will this over-release the property?
Yazzmi
Yes, that approach leaks. It does not invoke the setter (which will release the old value); it just writes a new value over the old one. Since the old value is never released, it leaks. You must be certain to write `self.property = nil`, not `property = nil`.
Seamus Campbell
Note that you should not use self.myProperty = nil in a dealloc statement. There you should release the object directly so as to avoid triggering KVC notifications.
Kendall Helmstetter Gelner
@Kendall Yes, you are correct. I didn't think there was any suggestion of using assignment to nil in `-dealloc`. But I've updated my post to clarify.
Seamus Campbell