2016-05-06 18 views
0

在類MainLayer的init()函數中,我使用一個靜態向量來存儲擴展Node的類塊的指針。然後,5秒後(我使用一個計劃來觸發運行runBlock()函數),我嘗試獲取存儲在靜態向量中的數據。cocos2dx 3.10中的內存管理是什麼?

但是,我得到的數據是錯誤的。從調試中,我明白這是內存錯誤。我初始化的數據看起來像被刪除。

我不知道爲什麼數據被刪除。請幫助我,謝謝!

這裏是我的關鍵代碼:

MainLayer.cpp

std::vector<block*> MainLayer::block_array = std::vector<block*>(); 
bool MainLayer::init(){ 
    Layer::init(); 
    ... 
    //the schedule 
    schedule(schedule_selector(MainLayer::runBlock), 5.0f, CC_REPEAT_FOREVER, 0.0f); 

    //initialization the data 
    block* b1 = block1::create(); 
    block* b2 = block2::create(); 
    block* b3 = block3::create(); 
    block_array.push_back(b1); 
    block_array.push_back(b2); 
    block_array.push_back(b3); 
    this->addChild(b1->node); 
    this->addChild(b2->node); 
    this->addChild(b3->node); 

    return true; 
} 

void MainLayer::runBlock(float dt){ 
    Size size = Director::getInstance()->getVisibleSize(); 
    int len = block_array.size(); 
    int rand = floor(CCRANDOM_0_1()*len); 
    if (rand == len){ 
     rand -= 1; 
    } 

    //here is the problem, the memory which "bb" point is not be allocated 
    //by the way, the value of bb equals b1 when initialize the data (I mean the memory address is equal, but the data in memory is different) 
    block* bb = block_array[0]; 

    bb->come();   //this is function in class block 
} 

回答

0

我很愚蠢的!

儘管b1-> node是添加了圖層,但是b1沒有添加。所以在下一幀中,b1將被回收。

只是MainLayer ::的init()添加代碼

b1->retain(); 
b2->retain(); 
b3->retain(); 

一切都會正常

+1

不要忘記釋放後使用 – Striker

+0

'的cocos2d :: VECTOR'。它會自動保留和釋放元素。 – Zen