Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 927
Thanks Avatar asked Apr 07 '09 12:04

Thanks


2 Answers

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.

like image 196
Jaka Jančar Avatar answered Oct 20 '22 18:10

Jaka Jančar


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:

like image 26
Adam Alexander Avatar answered Oct 20 '22 16:10

Adam Alexander