0
votes

I am working on a cocos2d project and want to work with an array of sprites.

I create the array:

NSMutableArray *ssprites;

Then I add stuff to it in the init method:

CCSprite *obssprite = [CCSprite spriteWithFile:@"/Users/Desktop/Programs/physics test/physics test/Resources/[email protected]"];  
            obssprite.position=ccp(position,5);

            [self addChild: obssprite];

            [ssprites addObject: obssprite];

Then later I want to remove sprites:

for( int i=0; i<[ssprites count];i++) {
    CCSprite *spr = (CCSprite *) [ssprites objectAtIndex:i];
        if(YES) {    //this is just for test, the actual program uses an actual condition

            [spr removeFromParentAndCleanup: YES];
            [ssprites removeObjectAtIndex:i];
        }


}

But for some reason the sprites are staying on the screen. How should I fix the code to actually remove the sprites?

2
i < [ssprites count] and then [ssprites removeObjectAtIndex:i] will cause issues. - Joe
I can't find any wrong in your code, maybe you have to review other part of code. - Reck Hou

2 Answers

1
votes

As Joe mentioned in his comment you are looping through the array of sprites and removing them in the loop itsels. So, the first time you remove the object at index 0 and then increment i to 1, which now actually "points" to the object at index 2 in your original array (the one that was at index 1 before is now at index 0). It seems to me that you are removing every second object?

Regardless of this issue, it is never a good idea to delete elements from the array you are looping through. Do you need this array at all? What if you simply used CCNode's children array (from your code it seems that every sprite is added to the parent and your own array of sprites).


You can see this in action with this simple code

NSMutableArray *ssprites = [NSMutableArray arrayWithObjects:@"obj1", @"obj2", @"obj3", @"obj4", @"obj5", nil];
for(int i = 0; i < [ssprites count]; i++) 
{
    NSString *spr = (NSString *) [ssprites objectAtIndex:i];

    NSLog(@"removing %@", spr);

    [ssprites removeObjectAtIndex:i];
}

I suggest you change your code like this

NSMutableArray *spritesToRemove = [[NSMutableArray alloc] init];

for (CCSprite *spr in ssprites)
{
    if (YES) // Your condition goes here
    {
        // Remove the sprite from its parent here.
        [spr removeFromParentAndCleanup:YES];
        // However, leave the "spr" in ssprites array - just "mark" it for deletion.
        [spritesToRemove addObject:spr];
    }
}

[ssprites removeObjectsInArray:spritesToRemove];
0
votes

Try:

//..
[self removeChild:spr cleanup: YES]
//..