0

我在触摸事件中收到 EXC BAD ACCESS 错误。突出显示的行是:

if ([aCrate isKindOfClass:[Crate class]]) {

我正在使用 cocos2d 在启用 ARC 的项目中工作。我不知道为什么会发生此错误,并且可以使用一些帮助调试。

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[AppData sharedData]isGamePaused] == NO) {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    for (Crate* aCrate in self.children) {
        if ([aCrate isKindOfClass:[Crate class]]) {

            if ([self collisionWithPoint:location andRadius:40 andPoint:aCrate.crateSprite.position andRadius:aCrate.crateSprite.contentSize.width/2] && [aCrate isDestroyed] == NO) {
                CGPoint crateLocation = aCrate.crateSprite.position;
                [self crateTouched:crateLocation];

                ScoreNode* aScore = [ScoreNode createWithScore:[[objectDict objectForKey:@"CrateHit"]integerValue]];
                aScore.position = aCrate.crateSprite.position;
                [self addChild:aScore z:zScoreNode];

                [aCrate destroyed];

                score = score + 50;
            }

        }
    }
}

}

我用这个代码添加了 Crate 对象,并且它没有在任何地方被删除

Crate* aCrate = [Crate createWithDictionary:crateDict];
[self addChild:aCrate z:zCrate];

它让我发疯,所以任何帮助都会很棒

4

1 回答 1

1

我想当你打电话时

[aCrate destroyed];

您正在使用 removeChild 或 removeFromParentWithCleanup 从子数组中删除它,对吗?

如果是这样,这会修改 children 数组,这在枚举期间是非法的。您必须将要销毁的 crate 添加到 NSMutableArray 并在方法结束时执行以下操作:

NSMutableArray* toBeDestroyed = [NSMutableArray array];

for (Crate* aCrate in self.children) {
    if ([aCrate isKindOfClass:[Crate class]]) {
        ...
        if (needsToBeDestroyed) {
            [toBeDestroyed addObject:aCrate];
        }
    }
}

// now you can destroy them
[toBeDestroyed makeObjectsPerformSelector:@selector(destroyed)];
于 2013-04-26T16:37:46.700 回答