【问题标题】:Error '*** Collection <__NSCFDictionary: 0x563560> was mutated while being enumerated.'错误“*** 集合 <__NSCFDictionary: 0x563560> 在枚举时发生了突变。”
【发布时间】:2011-12-27 02:05:43
【问题描述】:

此代码导致错误,可能是什么问题? 我读过一些关于锁的东西,不可变对象在多个线程上使用时很容易崩溃。但我真的不知道那是怎么回事......

-(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];
            } 

        }  


}

【问题讨论】:

  • 我认为这是因为您在枚举字典时正在修改字典.... [existingHexagons removeObjectForKey:spriteKey];是导致错误的地方。

标签: iphone objective-c ios ipad cocos2d-iphone


【解决方案1】:

要枚举这种情况下的所有键,您可以使用

for (spriteKey in [existingHexagons allKeys])

因此您可以在枚举时修改字典。但是,如果您仍然要删除所有键,您不应该在循环后使用removeAllObjects 方法清空字典吗?

【讨论】:

    【解决方案2】:

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

    所以在你的代码中你不能这样做

    [existingHexagons removeObjectForKey:spriteKey];
    

    内部

    for (spriteKey in existingHexagons)
    

    因为你正在修改existingHexagons
    您将需要使用常规的for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多