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

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

iphone - Objective-C NSMutableArray mutated while being enumerated?

I kinda stumbled into the error where you try to remove objects from an NSMutableArray while other objects is being added to it elsewhere. To keep it simple, i have no clue on how to fix it. Here is what i'm doing:

I have 4 timers calling 4 different methods that adds an object to the same array. Now, when i press a certain button, i need to remove all objects in the array (or at least some). So i tried to first invalidate all the 4 timers, and then do the work i want with the array, and then fire up the timers. I thought this would've worked since i am not using the timers anymore to enumerate through the array, but seemingly it doesn't work.

Any suggestions here?

question from:https://stackoverflow.com/questions/8834031/objective-c-nsmutablearray-mutated-while-being-enumerated

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

1 Answer

0 votes
by (71.8m points)

It's nothing to do with your timers. Because (I assume) your timers are all working on the same thread as your modifying method you don't need to stop and start them. iOS doesn't use an interrupt model for timer callbacks, they have to wait their turn just like any other event :)

You're probably doing something like

for (id object in myArray)
   if (someCondition)
       [myArray removeObject:object];

You can't edit a mutable array while you're going through it so you need to make a temporary array to hold the things you want to remove

// Find the things to remove
NSMutableArray *toDelete = [NSMutableArray array];
for (id object in myArray)
   if (someCondition)
       [toDelete addObject:object];

// Remove them
[myArray removeObjectsInArray:toDelete];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...