3

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];
         }
      }
   }
}
NSologistic
  • 745
  • 4
  • 14
  • I've seen you want to solve also this http://stackoverflow.com/questions/38525232/replacing-calayer-and-cabasicanimation-with-skscene-and-skactions , I've update my answer please take a look (I write to you here because you aren't in comments or conversations) – Alessandro Ornano Aug 24 '16 at 07:58

1 Answers1

0

Do not remove objects from array while iterating over it.

Andrew
  • 24,218
  • 13
  • 61
  • 90
  • ok. Now I am populating another array with off screen balls to be destroyed. This is done within the if block. `[destroyBallArray addObject:ballPhysicsSprite];`. I am finding it a bit tricky making sure that each off screen ball is added to the array only once, since this is called in the update method. – NSologistic Sep 01 '13 at 15:52
  • just use the reverseEnumerator, then you can delete the currently enumerated object safely – CodeSmile Sep 01 '13 at 19:53