Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

NSArray was mutated while being enumerated

I know this is because I'm deleting objects from the array while also enumerating through it, invalidating the enum.

What I want to know is what is the best strategy to solve this going forward? I've seen a few solutions online: @synchronized, copying the array before enumerating or putting the touch joint into a garbage array for later deletion (which I'm not sure would work, because I need to remove the mousejoint from the array straight after removing it from the world).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
668 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can always iterate without an enumerator. Which means a regular for loop, and when you remove an object:- decrement the index variable and continue;. if you are caching the array's count before entering the for-loop, then make sure you decrement that too when removing an object.

Anyway, I do not see why an array with objects for later removal would be a problem. I do not know the exact situation which you are having and the technologies involved, but theoretically there should not be a problem. Because in most cases when using this method you can just do nothing in the first enumeration, and do the real work when enumerating the removal array. And if you have a situation where in the first enumeration you are checking something again against the same array and you need to know that the objects are not there anymore, you can just add a check to see if they are in the removal array.

Anyway, hope I helped. Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...