0

在觸摸事件中,我正在獲取EXC BAD ACCESS錯誤。被突出顯示的行是:觸摸事件中的EXC BAD ACCESS錯誤

如果([aCrate isKindOfClass:[木箱類]]){

im使用的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* aCrate = [Crate createWithDictionary:crateDict]; 
[self addChild:aCrate z:zCrate]; 

它快把我逼瘋了,所以任何幫助將是巨大的

回答

1

我相信當你致電

[aCrate destroyed]; 

你正在通過使用removeChild或removeFromParentWithCleanup從兒童數組中刪除它,是否正確?

如果是這樣會修改子數組,這在枚舉過程中是非法的。你將不得不添加待銷燬的箱子到一個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)];