destroying an array of CCPhysicsSprites

117 Views Asked by At

In my code below, which I call in the update method, the CCPhyscisSprites are removed and their bodies are destroyed when array elements are off the screen. I put a CCLOG to check the array count and I always get 1 when all the sprites are off screen. Though I don't see the sprite, it's most likely still around. What could be the cause and how can I solve it?

-(void)ballScheduler   {

if (ballArray != NULL) {
    for (int i = 0; i < ballArray.count; i++) {
        CCLOG(@"ball array count is %d", ballArray.count);
        CCPhysicsSprite* ballPhysicsSprite = [ballArray objectAtIndex:i];
        b2Vec2 ballForce = b2Vec2(forceX, forceY);
        ballPhysicsSprite.b2Body->ApplyForce(ballForce, ballPhysicsSprite.b2Body->GetWorldCenter());

          if (ballPhysicsSprite.position.x < -ballPhysicsSprite.contentSize.width/2) {
              ballWorld->DestroyBody(ballPhysicsSprite.b2Body);
              ballPhysicsSprite.b2Body = NULL;
              [ballArray removeObject:ballPhysicsSprite];
              [ballBatchNode removeChild:ballPhysicsSprite];
         }
      }
   }
}
1

There are 1 best solutions below

2
On

Do not remove objects from array while iterating over it.