What explains best the difference between [myVar dealloc] and [myVar release]?
Asked Answered
E

2

7

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?

Essie answered 7/4, 2009 at 12:25 Comment(0)
G
13

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.

Gildus answered 7/4, 2009 at 12:32 Comment(0)
P
7

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:

Primitivism answered 7/4, 2009 at 12:36 Comment(3)
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]; }Essie
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]; }Melmon
I see you're reading Beginning iPhone 3 Development - Exploring the SDK (I am too, I recognized the yellow/blue view controller project).Salesin

© 2022 - 2024 — McMap. All rights reserved.