此代码导致错误,可能出错? 我读了一些关于锁的东西,并且当在多个线程上使用时,不可变对象可能容易崩溃。但实际上我不知道那是什么......
-(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 :(得分:4)
要在这种情况下枚举所有键,您可以使用
for (spriteKey in [existingHexagons allKeys])
因此您可以在枚举时修改字典。但是,如果您要删除所有键,不应该使用removeAllObjects
方法在循环后清空字典吗?
答案 1 :(得分:2)
您无法修改正在使用快速枚举的对象。
所以在你的代码中你不能做到
[existingHexagons removeObjectForKey:spriteKey];
里面的
for (spriteKey in existingHexagons)
因为您正在修改existingHexagons
您需要使用常规for
循环。