带有CallFunc回调的cocos2d向量。失去记忆

时间:2017-06-03 13:01:52

标签: c++ cocos2d-x

我在mainScene得到了矢量:

std::vector<CallFunc*> callbacksToSchedule;

在init()方法:

auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {
                                                      for(auto callFunc: callbacksToSchedule){
                                                          log(std::to_string(callFunc->getTag()).c_str());
                                                          callFunc->execute();
                                                      }
                                                  }, this,
                   RESOURCES_UPDATE_TIME, true, "schedulerKey");

处理以退出代码139结束(由信号11:SIGSEGV中断)

输出:

  

1952803683

但应该是:

  

100

1 个答案:

答案 0 :(得分:0)

updateCallBack结束时发布

init()。因为retainCount为零而从内存中清除。当你需要在实例变量中使用它们时,你必须保留它们。

auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
updateCallBack->retain();                      // retain updateCallBack
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {

        for(auto callFunc: callbacksToSchedule){
            CCLOG("%d TAG VALUE",callFunc->getTag());
            callFunc->execute();
        }
    }, this,RESOURCES_UPDATE_TIME, true, "schedulerKey");