Background:
Cocos Version: 3.0alpha
Language: C++
Problems:
Within one CCARRAY_FOREACH, it returned wrong&duplicated Object when removed one Object from the previous cycle.
Test Codes:
__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);
}
Output:
[Enum] Index: 0 Get: 90DFB88
[Enum] Index: 1 Get: 90E0030
[Enum] Index: 2 Get: 90E04D8
[Rmoved] Index: 0 Get: 90DFB88
[Rmoved] Index: 1 Get: 90E04D8
[Rmoved] Index: 2 Get: 90E04D8
Questions:
Is there anything wrong I did? I checked the codes with other developers' posted on the internet. It seems almost same.
I am curious no one met this problem before.
If not, we have to patch this hole in our codes when using CCARRAY_FOREACH?
Probably the better solution should use std::vector or 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;
}
}