I've learned that in dealloc
you do [object release];
but in viewDidUnload
(in a UIViewController subclass) you do self.object = nil
. What is really the difference because self.object = nil
(we're assuming object is a (nonatomic, retain)
property) retains nil
(which does nothing) and then releases the old value and then the reference count is 0 right?
views:
1552answers:
2self.object = nil
calls your setter, which will release the old value, set the member to nil
, and possibly do other things (it's a method, so it could do anything). The "anything" part of that is potentially dangerous; see this question, for example.
[object release]
releases the old value, but leaves the member as a now-dangling pointer, which is a good recipe for bugs. In dealloc
it doesn't really matter, since the pointer itself is about to go away too, but in any other case it's a very bad idea to release a member without setting it to nil
.
(As a sidenote, you should never assume that releasing an object gives it a reference count of 0. It releases your reference, but other objects may still have references to it.)
How does this affect situations when you have several pointers pointing to an object, and one of those pointers is set to nil? This doesnt affect the object that its pointing to right?
I ask this because ive seen a couple of situations where after setting an object reference to nil the app crashes (on iphone emulator).
Wondering if this is because of the setter that you mentioned above?