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
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.
-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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With