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?
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];
You can do it this way:
for (id object in [myArray copy])
if (someCondition)
[myArray removeObject:object];
Like @deanWombourne said, "you can't edit a mutable array while you're going through it", so what i'm doing here is to create an autoreleased copy of your original array to enumerate the objects, so you can safely remove anything you want.
More clear and less boiler code (i think!).
Update: Removed autorelease call since this was an old answer, pre ARC.
You can use the @synchronized() directive to lock the array while you mutate it:
if (someCondition) {
@synchronized(yourArray) {
[yourArray removeObject:someObject];
}
}
More info at http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocThreading.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With