NSMutableArray thread safety

ios, nsmutablearray, objective-c, thread-safety

Solution

I believe this solution is poor. Consider this:

- thread #1 calls `count` and is told there are 4 objects in the array.

- array is unsynchronized.

- thread #2 calls `removeObjectAtIndex:2` on the array.

- array is unsynchronized.

- thread #1 calls `objectAtIndex:3` and the error occurs.

Instead you need a locking mechanism at a higher level where the lock is around the array at both steps 1 and 5 and thread #2 cannot remove an object in between these steps.

Problem

In my app I'm accessing and changing a mutable array from multiple threads. At the beginning it was crashing when I was trying to access an object with `objectAtIndex`, because index was out of bounds (object at that index has already been removed from array in another thread). I searched on the internet how to solve this problem, and I decided to try this solution .I made a class with `NSMutableArray` property, see the following code: ``` @interface SynchronizedArray() @property (retain, atomic) NSMutableArray *array; @end @implementation SynchronizedArray - (id)init { self = [super init]; if (self) { _array = [[NSMutableArray alloc] init]; } return self; } -(id)objectAtIndex:(NSUInteger)index { @synchronized(_array) { return [_array objectAtIndex:index]; } } -(void)removeObject:(id)object { @synchronized(_array) { [_array removeObject:object]; } } -(void)removeObjectAtIndex:(NSUInteger)index { @synchronized(_array) { [_array removeObjectAtIndex:index]; } } -(void)addObject:(id)object { @synchronized(_array) { [_array addObject:object]; } } - (NSUInteger)count { @synchronized(_array) { return [_array count]; } } -(void)removeAllObjects { @synchronized(_array) { [_array removeAllObjects]; } } -(id)copy { @synchronized(_array) { return [_array copy]; } } ``` and I use this class instead of old mutable array, but the app is still crashing at this line: `return [_array objectAtIndex:index];` I tried also this approach with `NSLock`, but without a luck. What I'm doing wrong and how to fix this?

Original source

Related problems