UIButton事件函数中删除自身导致崩溃 和 触摸事件继续传递

来源:互联网 发布:大城市生活 知乎 编辑:程序博客网 时间:2024/06/06 07:36

方法2 node->runAction(RemoveSelf::create()); 同时可解决触摸事件继续传递问题


回调函数里判断是弹起事件时会调用UIButton的removeFromParent方法,这时会导致游戏崩溃,代码中断在void Widget::onTouchEnded(Touch *touch, Event *unusedEvent)方法里的releaseUpEvent()调用处.


1.修改引擎代码

void Widget::releaseUpEvent(){    if (_touchEventListener && _touchEventSelector)    {        (_touchEventListener->*_touchEventSelector)(this,TOUCH_EVENT_ENDED);    }        if (_touchEventCallback) {        _touchEventCallback(this, TouchEventType::ENDED);    }}

换个位置就好了

调用callback完以后释放本对象,但代码没执行完 继续调用Listener,这时释放的地址很可能不为空,就导致出错了

2.不需要修改引擎代码

删除自身的时候

改用 node->runAction(RemoveSelf::create()); 

代替原来的removefromparentandcleanup(true);

原理:我们可以看看引擎对removeSelf的实现

不直接调用remove,而是设置一个标志,在update中检测到标志再remove.  

//// Remove Self//RemoveSelf * RemoveSelf::create(bool isNeedCleanUp /*= true*/) {RemoveSelf *ret = new RemoveSelf();if (ret && ret->init(isNeedCleanUp)) {ret->autorelease();}return ret;}bool RemoveSelf::init(bool isNeedCleanUp) {_isNeedCleanUp = isNeedCleanUp;return true;}void RemoveSelf::update(float time) {CC_UNUSED_PARAM(time);_target->removeFromParentAndCleanup(_isNeedCleanUp);}RemoveSelf *RemoveSelf::reverse() const{return RemoveSelf::create(_isNeedCleanUp);}RemoveSelf * RemoveSelf::clone() const{// no copy constructorauto a = new RemoveSelf();a->init(_isNeedCleanUp);a->autorelease();return a;}


0 0
原创粉丝点击