I am attempting to populate one NSMutableArray with objects from a second NSMutableArray while inside of a For loop for the second array. When I add an object to the first array I am kicked out of the loop. This is occurring inside of a ‘schedule’ callback in a COCOS2D application.
The weird thing is it works fine in one case but not in another. The first time it works is noted below in the code sample. The second time is also noted in code, with the relevant line denoted with 5 *’s. The only thing that is fundamentally different is that the second example happens over and over inside of a While loop, constantly filling and emptying the second NSMutableArray.
Something is clearly happening that I just don’t understand. I’m hoping that someone will be able to catch it.
Thanks in advance for the help!
The following code is the relevant part of the method:
NSMutableArray *gameSprites = [[NSMutableArray alloc] init];
NSMutableArray *guns = [[NSMutableArray alloc] init];
NSMutableArray *newGuns = [[NSMutableArray alloc] init];
// START OF THE FIRST EXAMPLE
// collect sprites that are guns
for (LPSprite *sprite in gameSprites)
{
if ([sprite isGun])
{
[guns addObject:gun];
}
}
// END OF THE FIRST EXAMPLE
// do work for all guns in gamesprite collection
int numGuns = [guns count];
while (numGuns > 0)
{
// START OF THE SECOND EXAMPLE
for (LPGun *gun in guns)
{
if (special condition that only occurs sometimes)
{
LPGun *portalGun = [[LPGun alloc] init];
// ***** When this line is executed, I get 'kicked' out of the method and execution starts again at the beginning of the method. No exception is thrown or noticed.
[newGuns addObject:portalGun];
}
}
numGuns = [newGuns count];
// empty gun collection and add any 'new' guns to the collection so the above work can be repeated
[guns removeAllObjects];
for (LPGun *g in newGuns)
{
[guns addObject:g];
}
[newGuns removeAllObjects];
// END OF THE SECOND EXAMPLE
}
As mentioned in one of my comments above:
Adding some logging helped. It forced me to look at the console log which was actually spewing out an error (or maybe a warning) that was preventing the object from being added to the array. The init line just above the add was failing because a texture could not be found.
So I misinterpreted the symptoms, and as a result the topic here may be a bit misleading to people visiting it in the future.