addChild vs CC_SAFE_RETAIN

Ok, I’m trying desperately to get my memory management under control. I clearly don’t understand the difference between calling CC_SAFE_RETAIN on CCObjects I need and just creating a large ‘tree’ structure with addChild.

From what I can see, they both call retain(). So why can’t I just make all my various CCObjects children of my various CCLayers, which are in turn children of my CCScene? If I put a corresponding removeFromParent call in the destructor of all my parents, shouldn’t things be nice and clean?

Why do I need CC_SAFE_RETAIN?

Thank you very much!

Just use addChild()

auto s = Sprite::create("cocos.png");
addChild(s);

simple :slight_smile:

If you have an object thats not on the tree(scenegraph), but you still want to keep it, then use retain()

1 Like

addChild adds your object to the scene and releases it when it’s removed from its parent, such as when its parent is removed. That means the object’s memory is managed automatically.

If you use CC_SAFE_RETAIN, which appears to just be a retain call that is skipped if the object is null, then you will need to manually release the object when you have finished with it, i.e. manual memory management.

I agree with nite; just use addChild unless you’re not adding the object to your scene.

2 Likes

Ok thank goodness. Haha, this is starting to make sense.

Thanks guys!