Cocos2d x 为什么不是';移除Sprite时是否移除t touch listener?

Cocos2d x 为什么不是';移除Sprite时是否移除t touch listener?,cocos2d-x,cocos2d-x-3.0,Cocos2d X,Cocos2d X 3.0,我有以下代码用于检查精灵的触摸: void SpriteBlock::addEvents() { auto listener = cocos2d::EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event) { Vec2 p = to

我有以下代码用于检查精灵的触摸:

void SpriteBlock::addEvents()
{
auto listener = cocos2d::EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);

listener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event)
{
    Vec2 p = touch->getLocation();
    Rect rect = this->getBoundingBox();

    if(rect.containsPoint(p))
    {
        return true; // to indicate that we have consumed it.
    }

    return false; // we did not consume this event, pass thru.
};

listener->onTouchEnded = [=](cocos2d::Touch* touch, cocos2d::Event* event)
{
    SpriteBlock::touchEvent(touch);
};

cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 30);
}


void SpriteBlock::touchEvent(cocos2d::Touch* touch)
{
}
这似乎工作得很好,但即使在精灵被销毁后,它仍然会被触发(如果我单击精灵最后一个存在的地方),并且它会崩溃:

"

线程1:EXC\u错误访问(代码=2,地址=0x7…)

"

在以下行:

    Rect rect = this->getBoundingBox();
现在我很清楚精灵被破坏了,因为我的析构函数被设置为在触发时显示一条日志消息(确实如此):

那么这里的问题是什么?为什么听众没有被我的精灵摧毁?我通过以下方式摧毁我的精灵:

    mysprite->removeFromParent();
创建精灵时,不存储任何引用。我只是将它添加到场景的主层,所以它不应该保留。我使用以下方法创建它:

SpriteBlock *block = SpriteBlock::create();
如何确保移除精灵时也移除了触摸侦听器

auto listener = cocos2d::EventListenerTouchOneByOne::create();
将其作为变量存储在SpriteBlock类中

然后在SpriteBlock析构函数中删除侦听器

将其作为变量存储在SpriteBlock类中


然后在SpriteBlock析构函数中删除一个侦听器。

Right-它在cocos2d站点的另一个页面上提到过,但在解释如何使用侦听器的文章中没有明确说明。显然,某些类型的侦听器是自动删除的,但是像这样的类型需要显式删除。@Makalele您能详细描述一下如何在析构函数中删除侦听器吗?cocos2d::Director::getInstance()->getEventDispatcher()->removeEventListener(侦听器);右-cocos2d网站上的另一个页面上提到了它,但在解释如何使用侦听器的文章中没有提到。显然,某些类型的侦听器是自动删除的,但是像这样的类型需要显式删除。@Makalele您能详细描述一下如何在析构函数中删除侦听器吗?cocos2d::Director::getInstance()->getEventDispatcher()->removeEventListener(侦听器);
auto listener = cocos2d::EventListenerTouchOneByOne::create();