children_
(CCArray
)的计数输出15,我收到错误:
'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];
}
}
我该如何解决这个问题?尝试删除所有标签以更改其字符串值。 在我的CCLayer上,我还有一些CCMenuItemLabel和CCMenuItemLabelAndSprite ......
答案 0 :(得分:4)
看起来你想要在集合类中向后迭代,所以你需要执行i--
来修改索引变量:
for (NSInteger i=[children_ count]-1; i>=0; i--) {
CCNode *c = [children_ objectAtIndex:i];
if ([c isKindOfClass:[CCLabelTTF class]]) {
[c removeFromParentAndCleanup:YES];
}
}
答案 1 :(得分:3)
如果可能,您应该使用fast enumerating:
for (id obj in [childres_ reverseObjectEnumerator]){
if ([obj isKindOfClass:[CCLabelTTF class]]) {
[obj removeFromParentAndCleanup:YES];
}
}
或使用block syntax
[children_ enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
if ([obj isKindOfClass:[CCLabelTTF class]]) {
[obj removeFromParentAndCleanup:YES];
stop= YES;
};
}];
答案 2 :(得分:2)
您似乎正在使用count-1初始化for循环计数器并递增,因此i的第一个值为14,而下一个值为15(超出范围)
试试这个:
for (NSInteger i=0; i<[children_ count]; i++) {
}