Search code examples
c++cocos2d-x

About behavior of CCArray


I have a question about CCArray. I wrote the code as follows.

h.file

class GameScene : public cocos2d::CCLayer{

public:
    CCArray *arrayA;
    CCArray *arrayB;

    void funcA();
    void funcB();

    CREATE_FUNC(GameScene);

}

cpp.file

void GameScene::funcA()
{
    arrayA = new CCArray;
    arrayB = new CCArray;


    //---------------About arrayA-------------------------
    CCDictionary *plist = CCDictionnary::createWithContentsOfFile("Data.plist");    
    arrayA = (CCArray*) plist->objectForKey("fruit");

    CCLog("size of arrayA is %d ",arrayA->count() );  //ok (size = 3)


    //---------------About arrayB-------------------------
    CCSprite *obj =CCSprite::create("sample.png");
    arrayB->addobject(obj);

    CCLog("size of arrayB is %d ",arrayB->count() );  //ok (size = 1)


    funcB();

}




void GameScene::funcB()
{
    CCLog("size of arrayA is %d ",arrayA->count() );   // appear the error (size = 102938312)
    CCLog("size of arrayB is %d ",arrayB->count() );   // ok (size = 1)
}

Detail of Data.plist

<plist version="1.0">
<dict>
    <key>fruit</key>
    <array>
        <string>apple</string>
        <string>orange</string>
        <string>strawberry</string>
    </array>
</dict>
</plist>

In funcA, I declared CCArrayA and CCArrayB. I added an obj to each array in a different way.

Next, each array showed each size of the array using CCLog, then neither array appear or the error.

But, in func B, though arrayB didn't change size same as time of funcA, arrayA change size to a strange value.

Why did such a thing happen?

By any chance, when escape from funcA, CCArrayA is released?

In that case, what should I do to prevent CCArrayA from releasing?


Solution

  • If you are getting array from plist file then you don't need to create it using new operator. Just assign to a member pointer of CCArray* and if you want to access it in all member functions then you have to retain it after assignment. Otherwise it will be released and throw exception or become garbage when control reaches out of function.