How to retain a sprite

Hi. I initialized a Sprite in a method. And I added this Sprite to the scene in another method (after initializing it, of course). But when I add it, it gives me this error:

> Assert failed: Argument must be non-nil
> Assertion failed!

> Program: ...le\MyCppGame\proj.win32\Debug.win32\libcocos2d.dll
> File: CCNode.cpp
> Line: 1103

> Expression: child != nullptr

I think the cause of this error is autorelease. I mean the sprite object is being autoreleased before I can add it to scene. Because I initialized it in different method, and used it in different method. And I heard “retaining” a sprite avoids autorelease. How to do that. thanks

C++: sprite->retain();
JavaScript: sprite.retain();

After adding it to a scene (probably using addChild) remember to release it, which just requires using the retain function on the sprite.

Another thing to consider if that if you choose to manage memory yourself, you should adopt a defensive programming pattern of doing so that is robust enough to prevent accidentally over releasing the object you retain.

The simplest defensive technique for this is to avoid having to retain the object. But sometimes it is necessary.

When I have a need to retain a Cocos2d-x node based object, I will always implement the constructor and destructor in the class that is going to do the retaining of the object.

Then do the following:
1) set the variable to nullptr in the constructor.
2) use CC_SAFE_RETAIN(_varibleName) macro to retain the object after it is created,
3) use CC_SAFE_RELEASE_NULL(_varibleName) macro to release the variable and set _varibleName = nullptr if the _varibleName is destroyed before the class that owns it needs to be destroyed.
4) in the destructor, always put CC_SAFE_RELEASE_NULL(_varibleName) to ensure you don’t accidentally have a memory leak.

1 Like