I have a question regarding thread safety in Objective-C. I\'ve read a couple of other answers, some of the Apple documentation, and still have some doubts regarding this, s
Subclass NSMutableArray to provide locking for the accessor (read and write) methods. Something like:
@interface MySafeMutableArray : NSMutableArray { NSRecursiveLock *lock; } @end
@implementation MySafeMutableArray
- (void)addObject:(id)obj {
[self.lock lock];
[super addObject: obj];
[self.lock unlock];
}
// ...
@end
This approach encapsulates the locking as part of the array. Users don't need to change their calls (but may need to be aware that they could block/wait for access if the access is time critical). A significant advantage to this approach is that if you decide that you prefer not to use locks you can re-implement MySafeMutableArray to use dispatch queues - or whatever is best for your specific problem. For example, you could implement addObject as:
- (void)addObject:(id)obj {
dispatch_sync (self.queue, ^{ [super addObject: obj] });
}
Note: if using locks, you'll surely need NSRecursiveLock, not NSLock, because you don't know of the Objective-C implementations of addObject, etc are themselves recursive.