当Ccarray_foreach中删除一个对象时,就会发生问题

Problems occurs when removed one object within Cocos CCARRAY_FOREACH

本文关键字:问题 一个对象 Ccarray foreach 删除      更新时间:2023-10-16

背景

  1. 可可版本 :3.0alpha

  2. 语言 :C

问题

在一个ccarray_foreach中,当从上一个周期中删除一个对象时,它返回错误&重复的对象。

测试代码

__Array* test = __Array::create();
test->retain();
Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();
test->addObject(item1);
test->addObject(item2);
test->addObject(item3);
Object *it = NULL;
int index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Enum] Index: %d Get: %X", index++, it);
}
it = NULL;
index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Rmoved] Index: %d Get: %X", index++, it);
    test->removeObject(it);
}

输出

[枚举]索引:0获取:90DFB88

[枚举]索引:1获取:90E0030

[枚举]索引:2获取:90E04D8

[rmaved]索引:0获取:90DFB88

[rmaved]索引:1 get: 90E04D8

[rmaved]索引:2获取: 90E04D8

问题

我做错了吗?我与互联网上发布的其他开发人员一起检查了代码。看起来几乎一样。

我很好奇以前没人遇到这个问题。

如果没有,我们必须在使用 ccarray_foreach

时,必须在代码中修补这个孔

可能更好的解决方案应该使用std :: vector或cocos :: vector。

Vector<Sprite*>* test = new Vector<Sprite*>();
Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();
test->pushBack(item1);
test->pushBack(item2);
test->pushBack(item3);
int index = 0;
Vector<Sprite*>::iterator it = test->begin();
while (it != test->end())
{
    log("[Enum] Index: %d Get: %X", index++, *it);
    ++it;
}
index = 0;
it = test->begin();
while(it != test->end())
{
    log("[Rmoved] Index: %d Get: %X", index++, *it);
    if(isRemovable)
    {
        it = test->erase(it);
    }
    else
    {
        ++it;
    }
}
相关文章: