I have read that dealloc for an object will be called, only if retain count of that object becomes zero.
I am taking one object for UIColor in interface section and setting property
UIColor *currentColor;
@property (nonatomic, retain) UIColor *currentColor;
After using this object in the implemetation section, I am calling release method for this object in dealloc
-(void)dealloc
{
[currentColor release];
[super dealloc];
}
I am in doubt how dealloc will be called for this object, because I am not releasing the retained object anywhere. Thanks in advance.
Yes.
For the sake of simplicity, call the class that contains
currentColorobject asColorContainer. Now, if you create an instance ofColorContainerlike the following:the retain count for
containerColorbecomes 1.Suppose you create an instance of a
UIColorand you set that instance tocurrentColorproperty. In this case you can follow two different ways.In the first one you can create an instance like the following. If you use an instance method like
initWithRed:green:blue:alpha:you have to release memory explicitly.In the second way, instead, you could use a class method (+ symbol). In this case you don’t need to release memory explicity because the object created in that class method will be autoreleased at a certain point of your application lifetime.
Now suppose you release
containerColorobject. If the retain count forcontainerColoris equal to 1, releasing it from an object that uses it, it enables to call its dealloc method and, in consequence, to dismiss also the object referenced bycurrentColor.In this simple case study you have to note that the object referenced by
currentColoris completely removed from memory (dismissed) only if it has a retain count of 1. In fact, if you do thisyou create a memory leak (Do you understand way?).
To summarize, when you use
retain,copy,initornew(it’s the same ofalloc-init), you have always to call their counterpartsreleaseorautorelease.As a rule of thumb, you need always to balance the retain count for objects to avoid memory leaks.
So, as a methaphor you could think to memory like a tree. Suppose you have a parent (
containerColor) and a child (currentColor). If the parent (with a retain of count of 1) is released, it causes to call its dealloc method and free memory for its object. If in its dealloc method you release a child (with a retain count of 1) it causes to call its dealloc method and free memory. In the case a child has a retain count greater than one, you cause a memory leak.Hope it helps.
Edit
For further information you could read About Memory Management. Since iOS 5 Apple has introduced ARC. Automatic Reference Counting is a compiler machanism that provides automatic memory management of Objective-C objects. For info see Transitioning to ARC Release Notes.