Avoiding “NSArray was mutated while being enumerated”

后端 未结 10 1789
傲寒
傲寒 2020-11-29 06:07

I have an NSMutableArray that stores mousejoints for a Box2d physics simulation. When using more than one finger to play I\'ll get exceptions stating

10条回答
  •  臣服心动
    2020-11-29 06:24

    I had the same problem, and the solution is to enumerate the copy and mutate the original, as edc1591 correctly mentioned. I've tried the code and I'm not getting the error anymore. If you're still getting the error, it means you are still mutating the copy (instead of the original) inside the for loop.

    NSArray *copyArray = [[NSArray alloc] initWithArray:originalArray];
    
    for (id obj in copyArray) { 
        // tweak obj as you will 
        [originalArray setObject:obj forKey:@"kWhateverKey"];
    }
    

提交回复
热议问题