3

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

Yazzmi
  • 1,541
  • 5
  • 18
  • 33

1 Answers1

4

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 Properties in dealloc: release then set to nil? or simply release.

Community
  • 1
  • 1
Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60
  • can I do property = nil in viewDidUnload and [property release] in dealloc? will this over-release the property? – Yazzmi Aug 16 '10 at 04:09
  • 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 Aug 16 '10 at 04:46
  • 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 Aug 16 '10 at 05:20
  • @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 Aug 16 '10 at 07:05