Austin
Austin

Reputation: 4929

App Crashing with NSMutableArray

I'm pretty new to iOS, and I have no idea how to find a decent stacktrace like JAVA, so all I can find on why it's crashing is, "sigabrt".

I know it has something to do with this code I just added.

-(void) clearGame {
    for (CCSprite *sprite in placedSprites) {
        if(sprite == nil) continue;
        [self removeChild:sprite cleanup:NO];
        [placedSprites removeObject:sprite];
    }
    placedSprites = [[NSMutableArray alloc] initWithCapacity:1000];
}

Where the class I'm adding this to is a Layer in cocos2d. In it's init method, I have

placedSprites = [[NSMutableArray alloc] initWithCapacity:1000];

I don't know what could be wrong, so any help is appreciated.

Thank you!

Upvotes: 2

Views: 902

Answers (1)

tilo
tilo

Reputation: 14169

You cannot remove an object from a NSMutableArray while fast-enumerating (see documentation).

You could add the objects (which should be removed) to a separate NSMutableArray and remove the objects from this array from your 'main' array:

NSMutableArray *discardedItems = [NSMutableArray array];
SomeObjectClass *item;

for (item in originalArrayOfItems) {
    if ([item shouldBeDiscarded])
        [discardedItems addObject:item];
}

[originalArrayOfItems removeObjectsInArray:discardedItems];

Also see Removing object from NSMutableArray and Best way to remove from NSMutableArray while iterating?.

Upvotes: 7

Related Questions