Search code examples
objective-ccocos2d-iphone

out of range in objectAtIndex objective c


The count of children_ (CCArray) outputs 15 and I'm receiving error:

'NSInternalInconsistencyException', reason: 'index out of range in objectAtIndex(14), index 15'

for (NSInteger i=[children_ count]-1; i>=0; i++) {

        CCNode *c = [children_ objectAtIndex:i];

        if ([c isKindOfClass:[CCLabelTTF class]]) {
            [c removeFromParentAndCleanup:YES];
        }
    }

How would I solve this? Trying to remove all the labels in order to change their string value. On my CCLayer I have have also some CCMenuItemLabel and CCMenuItemLabelAndSprite...


Solution

  • It looks like you want to iterate backwards through the collection class, so you need to perform i-- to modify the index variable:

    for (NSInteger i=[children_ count]-1; i>=0; i--) {
    
        CCNode *c = [children_ objectAtIndex:i];
    
        if ([c isKindOfClass:[CCLabelTTF class]]) {
            [c removeFromParentAndCleanup:YES];
        }
    }