Best practice for creating non cocos objects?

Say I want to create my own non cocos object. For example a custom level reader that bundles a bunch of functions I wrote. I also want to take advantage of the cocos memory management pool so I don’t have to worry about new/delete calls. So far my object is inheriting from Node class and has create and init functions as follows:

MyNode* MyNode::create()
{
    MyNode* myNode = new MyNode();

    if (myNode->init())
    {
	myNode->autorelease();
	return myNode;
    }

    CC_SAFE_DELETE(myNode);
    return NULL;
  }

bool MyNode::init()
{    
     if (!Node::init())
     {
	     return false;
     }   
     return true;
}

With the above code I could just create my object and add it to my scene. The object stays until I remove it or until the scene is removed, as expected.

My question is if this is the best practice for such a situation? I noticed that Node has a bunch of properties such as position, contentSize, etc. which really do not make sense for my level reading class. Is it possible to inherit one step lower from the cocos Ref class and still maintain the same functionality as I described? If so then what would be the equivalent create() and init() functions with regards to my above code.

I’m pretty sure Node is designed to be added to the scene and either be a visible component or have visible components added to it.

If you want memory management but don’t want it to be a Node, I imagine Ref would be what you are after. Just remember to retain it when you create it and release it when you’re done with it.

2 Likes

The reason I use Node despite not being a visible component or not having visible components added, is that I don’t need retain/release calls. I simply remove the parent and don’t have to worry about each of the children. So now I wonder if I could do something like this:

MyRef* myRef = MyRef::create();
myScene->addChild(myRef);

and then to clean up I just call:

Director::getInstance()->replaceScene(TransitionFade::create(1, newScene));

Would anything like this be possible with Ref? Or should I just stick with Node and stomach the extra overhead costs?

IMHO, you should always care about memory management. If this means you get the best results out of dealing with it manually you should do it. Relying in auto-release isn’t always full-proof. There could be bugs, etc. Dealing with it manually is almost a guarantee.

Looking at the API Ref, Ref doesn’t have a way to add children to it: http://cocos2d-x.org/docs/api-ref/cplusplus/v3x/df/d28/classcocos2d_1_1_ref.html I guess you could always make member variables in your MyRef class and do:

myScene->addChild(myRef->getSomething());
myScene->addChild(myRef->getSomething2());

In that case I’ll go with inheriting from Ref and manually retaining/releasing as grimfate mentioned.