错误'***集合<__ NSCFDictionary:0x563560>在枚举时发生了变化。'

问题描述:

此代码导致错误,可能是错误的? 我读了一些关于锁的内容,并且在多线程上使用时,不可变对象可能容易崩溃。但真的我不知道这是什么...错误'***集合<__ NSCFDictionary:0x563560>在枚举时发生了变化。'

-(void)cleanUpAllHexagons{ 

    //Cleaning up all hexagons from previous level 
    NSLog(@"cleaning hexagons"); 
    NSString *spriteKey; 
    NSString *touchAreaKey; 

    NSMutableDictionary *existingHexagons = [[GameStateSingleton sharedMySingleton]getExistingHexagons]; 

     for (int i= 0; i < [existingHexagons count]; i++){ 
      spriteKey = [NSString stringWithFormat:@"hexagon%d",i]; 

      for (spriteKey in existingHexagons) { 
       NSLog(@"the spritekey = %@",spriteKey); 
       NSLog(@"%@", existingHexagons); 
       NSLog(@"%@", [[existingHexagons valueForKey:spriteKey]objectForKey:@"realSprite"]); 
       [self removeChild:[[existingHexagons valueForKey:spriteKey]objectForKey:@"realSprite"] cleanup:YES]; 
       [existingHexagons removeObjectForKey:spriteKey]; 
      } 


      hexTouchAreas = [[GameStateSingleton sharedMySingleton]getSharedHexTouchAreas]; 

      touchAreaKey = [NSString stringWithFormat:@"hexTouchArea%d",i]; 

      for (touchAreaKey in hexTouchAreas) { 
       NSLog(@"the touchAreakey = %@",touchAreaKey); 
       NSLog(@"%@", [hexTouchAreas valueForKey:touchAreaKey]); 
       [self removeChild: [hexTouchAreas valueForKey:touchAreaKey] cleanup:YES]; 
      } 

     } 


} 
+0

我认为它是因为你正在修改字典,同时枚举它.... [existingHexagons removeObjectForKey:spriteKey]; 是导致错误的地方。 – Ravin 2011-12-27 08:17:29

枚举所有键在这种情况下,你可以使用

for (spriteKey in [existingHexagons allKeys]) 

所以,你可以修改的字典,而枚举。但是,如果您要删除所有密钥,请不要在循环后用​​方法清空字典?

+0

非常感谢你:)。 – 2011-12-27 12:30:57

你不能修改你正在使用快速枚举的对象。

因此,在你的代码,你不能做

[existingHexagons removeObjectForKey:spriteKey]; 

for (spriteKey in existingHexagons) 

里面因为要修改existingHexagons
您将需要使用正for循环。