Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is setting a property to nil same as releasing the property?

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?

like image 733
NSExplorer Avatar asked Jan 19 '23 16:01

NSExplorer


2 Answers

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.

like image 91
John Calsbeek Avatar answered Jan 29 '23 15:01

John Calsbeek


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.

like image 40
Anton Avatar answered Jan 29 '23 14:01

Anton