TheM00s3
TheM00s3

Reputation: 3711

Game crashes sporadically around checking for sprites

My game keeps crashing around this particular block of code.

The error message is Thread1: EXC_Bad_ACCESS(code =1) and the highlighted code is the following:

-(void)updateForArrays:(ccTime)delta
{
   for (CCSprite *child in [self children]){
        if (child.tag==2) {

            if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
                [self removeChild:child cleanup:YES];
                _score += 1;
                [_scoreLabel setString:[NSString stringWithFormat:@"Score : %d",_score]];
            }
        }if (child.tag ==3){
            if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
                CCScene *gameOverScene = [GameOverLayer gameOverScene];
                [[CCDirector sharedDirector] replaceScene:gameOverScene];

            }
        }
     }
}

Upvotes: 0

Views: 71

Answers (2)

SaffronState
SaffronState

Reputation: 329

If all the children of self is of type CCSprite then your code will work. If not then you will face a crash. Because there is a chance that you might be forcefully typecasting a child which is of no CCSprite class. See if this code helps

-(void)updateForArrays:(ccTime)delta
{
for (id item in [self children]){
    if((item isKindOfClass:(CCSprite class)])
    {
     CCSprite *child = (CCSprite *)item;
      if (child.tag==2) {

        if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
            [self removeChild:child cleanup:YES];
            _score += 1;
            [_scoreLabel setString:[NSString stringWithFormat:@"Score : %d",_score]];
        }
    }if (child.tag ==3){
        if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
            CCScene *gameOverScene = [GameOverLayer gameOverScene];
            [[CCDirector sharedDirector] replaceScene:gameOverScene];

        }
    }
   }
 }
 }

Upvotes: 0

Alexander
Alexander

Reputation: 8147

You shouldn't modify ([self removeChild:child cleanup:YES]) collections (the [self children] array) while iterating. One way to go around this is to add objects for removal in a separate array and remove them after you're done checking for collisions.

Edit:

NSMutableArray *cleanupArray = [NSMutableArray array];
for (CCSprite *child in [self children]) {
    // ...
    [cleanupArray addObject:child]; // instead of [self removeChild:child cleanup:YES];
    // ...
}

// actual removal of children
for (CCSprite *child in cleanupArray) {
     [self removeChild:child cleanup:YES];
}
[cleanupArray removeAllObjects];

Upvotes: 3

Related Questions