Here is the thing,
Object of the class Ref
or any class derived from it has a variable _retainCount
which represents the scope of the object.
Also there is an autorelease
pool which is similar to the garbage collector in java
. The object which is added to this autorelease
pool will be deleted at the end of the frame. Unless its _retainCount!=0
Now when you create new object of Ref
or derived class using the create method it is already added to the autorelease
pool and you don't need to release
it or delete
it anywhere. As you can see in the create function of Node
below.
Node * Node::create()
{
Node * ret = new (std::nothrow) Node();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
But when you create new object using 'new' you definitely need to delete
it after its use is over. Though it is not recommended to use New to allocate
the objects of cocos2d
classes. Rather use create.
Node* temp=Node::create();
then,
temp->retain();
//your work...
temp->release();
or
Node* temp=Node::create();
Node* tempChild=Node::create();
temp->addChild(tempChild);
//your work...
temp->removeFromParent();
Second thing,
when your object is added to the autorelease
pool but you need to increase its scope you could just retain it , this increments its retain count by one and then you have to manually release it i.e, decrement its retain count after its use is over.
Third Thing,
Whenever you add child your object it is retained automatically but you don't need to release
it rather you remove it from the parent as mentioned above.
Official documentation is @link below.
[http://www.cocos2d-x.org/wiki/Reference_Count_and_AutoReleasePool_in_Cocos2d-x#Refrelease-retain-and-autorelease][1]