在类MainLayer init()函数中,我使用静态向量来存储扩展Node的类块的指针。然后,在5秒后(我使用计划触发运行runBlock()函数),我尝试获取存储在静态向量中的数据。
然而,我得到的数据是错误的。从调试,我明白这是内存错误。我初始化的数据看起来像是被删除了。
我不知道数据被删除的原因。请帮帮我,谢谢!
这是我的密码:
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 :(得分:0)
我傻了!
虽然添加了b1-&gt;节点,但未添加b1。所以在下一帧中,b1将被回收。
只需在MainLayer :: init()中添加代码
b1->retain();
b2->retain();
b3->retain();
一切都会正常