Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between release and dealloc in objective-c

When deallocing a refrence I've seen release and dealloc being used for example

-(void)dealloc {   [foo release];   [nar dealloc];    [super dealloc]; } 

My question is when is release to be used and when is dealloc to be used?

Thanks

like image 365
hhafez Avatar asked Feb 18 '09 00:02

hhafez


People also ask

What is release in Objective-C?

The system that Objective-C uses is called retain/release. The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it. Similar to Java, each object has a retain count.

Is Dealloc a function?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application.

What method is automatically called to release objects in Objective-C?

Sending the autorelease message to an object marks it for autorelease. When the autorelease pool drains at the end of each event loop, it sends release to all the objects it owns. By convention, object-creation class methods return an autoreleased object.


2 Answers

Never call dealloc except as [super dealloc] at the end of your class's dealloc method. The release method relinquishes ownership of an object. When a Cocoa object no longer has any owners, it may be deallocated — in which case it will automatically be sent a dealloc message.

If you're going to program Cocoa, you need to read the Memory Management Guidelines. It's incredibly simple once you get over the initial hump, and if you don't understand what's in that document, you'll have lots of subtle bugs.

like image 81
Chuck Avatar answered Sep 19 '22 22:09

Chuck


The dealloc statement in your example is called when the object's retain count becomes zero (through an object sending it a release message).

As it is no longer needed, it cleans itself up by sending a release message to the objects that it is holding on to.

like image 23
Abizern Avatar answered Sep 18 '22 22:09

Abizern