views:

1552

answers:

2

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?

+8  A: 

self.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.)

smorgan
Note also that Apple specifically recommends against using setters/getters in init and dealloc (for good reasons), hence the use of [object release] in dealloc - its not just "In dealloc it doesn't really matter", in dealloc it is the recommended way.
Peter N Lewis
Right, I meant that having a non-nil pointer doesn't really matter (as in, you don't need to then do object=nil after the release in dealloc)
smorgan
Actually, with synthesized ivars, setters must be usd in dealloc. See http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1 search for the phrase "synthesizing the instance variable".
ustun
A: 

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?

Edward An
I don't think it affects the object it's pointing to. I think it's just like setting a pointer to `nil`. Still, your app can crash if you do `self.object = nil` because, as smorgan states above, that "calls your setter, which will release the old value" (assuming the property is declared with `retain`). And, if you release an object that already has a retain count of 0, you get a EXC_BAD_ACCESS error.
MattDiPasquale