What is the difference between
self.myObject = nil;
and
[myObject release];
Also, why is the former generally used in the viewDidUnload method and the latter used in the dealloc method?
Assuming a retain
property, then this:
self.myObject = nil;
will both release the object and set the value of the property to nil
. It will also do this through the setter method, possibly triggering KVO notifications. And this:
[myObject release];
will only release the object, leaving a dangling pointer in the property.
The latter is normally used in -dealloc
because you don't care about the value of the variable after the object has been deallocated, and also because you would rather not trigger KVO notifications from an object that's being destroyed. The former is used pretty much everywhere else.
John's answer is correct. Basically there is no need to set any value to any variable in dealloc
as the object is being garbage collected. I think that one can come up with a situation where the view is unloaded, but some methods will still be called. In this situation it is safe to set local variables to nil
in order to be able to send messages and not to get crashes.
There was a blog post by Jeff LaMarche some time ago about "to nill or not to nill". Have a look, espeсially at the last section.
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