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
The simplest way is to enumerate backwards through the array which means the next index won't be affected when you remove an object.
for (NSObject *object in [mutableArray reverseObjectEnumerator]) {
// it is safe to test and remove the current object
if (AddTestHere) {
[savedRecentFiles removeObject: object];
}
}
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"];
}
Lock (@synchronized) operation is much faster then copying entire array over and over again. Of course this depends on how many elements the array has, and how often is it executed. Imagine you have 10 threads executing this method simultaneously:
- (void)Callback
{
[m_mutableArray addObject:[NSNumber numberWithInt:3]];
//m_mutableArray is instance of NSMutableArray declared somewhere else
NSArray* tmpArray = [m_mutableArray copy];
NSInteger sum = 0;
for (NSNumber* num in tmpArray)
sum += [num intValue];
//Do whatever with sum
}
It is copying n+1 objects each time. You can use lock here, but what if there is 100k elements to iterate? Array will be locked until iteration is completed, and other threads will have to wait until lock is released. I think copying object here is more effective, but it also depends on how big that object are and what are you doing in iteration. Lock should be always keept for the shortest period of time. So I would use lock for something like this.
- (void)Callback
{
NSInteger sum = 0;
@synchronized(self)
{
if(m_mutableArray.count == 5)
[m_mutableArray removeObjectAtIndex:4];
[m_mutableArray insertObject:[NSNumber numberWithInt:3] atIndex:0];
for (NSNumber* num in tmpArray)
sum += [num intValue];
}
//Do whatever with sum
}
Using a for loop instead of enumerating is ok. But once you start deleting array elements, be careful if you're using threads. It's not enough to just decrement the counter as you may be deleting the wrong things. One of the correct ways is to create a copy of the array, iterate the copy and delete from the original.
edc1591 is the correct method.
[Brendt: need to delete from the original while iterating through the copy]