views:

932

answers:

2

I think I know the difference, but don't know how to explain that correctly.

dealloc removes the memory reserved by that variable totally and immediately.

release decrements the retain counter of that variable's memory by -1. if it was 1, then it's 0, so it would have the same effect as dealloc in that moment.

is that right? or is there an better short explanation?

+12  A: 

That's exactly right.

But you wouldn't use dealloc, when using an object, because you don't know what the retain count is. Nor do you care. You just say that you don't need it anymore, by calling release. And once nobody does, the object will call dealloc on itself.

Jaka Jančar
+5  A: 

All correct, but the one key point you're missing is that you should never call dealloc yourself. Here's some information from Apple's documentation on NSObject's dealloc method:

(from http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/dealloc)

You never send a dealloc message directly. Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0). See Memory Management Programming Guide for Cocoa for more details on the use of these methods.

Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super:

Adam Alexander
thanks. i think i'm a little bit confused now...so inside the dealloc methods of subclasses, i do have to dealloc my instance variables, right? ie - (void)dealloc { [yellowViewController dealloc]; [blueViewController dealloc]; [super dealloc];}
Thanks
Just to be clear, never call dealloc on anything except super. The proper implementation of Thanks' dealloc method is: -(void)dealloc { [yellowViewController release]; [blueViewController release]; [super dealloc]; }
rpetrich
I see you're reading Beginning iPhone 3 Development - Exploring the SDK (I am too, I recognized the yellow/blue view controller project).
Mk12