My question, in brief: Is there any way to make mutable collection KVO accessors thread-safe with the same lock that the @synthesized methods are locked?
Explanation: I have a controller class which contains a collection (NSMutableArray) of Post
objects. These objects are downloaded from a website, and thus the collection changes from time to time. I would like to be able to use key-value observing to observe the array, so that I can keep my interface updated.
My controller has a posts
property, declared as follows:
@property (retain) NSMutableArray *posts;
If I call @synthesize in my .m file, it will create the -(NSMutableArray *)posts
and -(void)setPosts:(NSMutableArray *)obj
methods for me. Further, they will be protected by a lock such that two threads cannot stomp on each other while setting (or getting) the value.
However, in order to be key-value coding compliant for a mutable ordered collection, there are a few other methods I need to implement. Specifically, I need to implement at least the following:
-insertObject:inPostsAtIndex:
-removeObjectFromPostsAtIndex:
However, since the posts are downloaded asynchronously, I would like to be able to insert new posts into the array on a background thread as well. This means that access needs to be thread-safe.
So, my question. Is there any way to make those accessors thread-safe with the same lock that the @synthesized methods are locked? Or do I have to resort to specifying the setPosts:
and posts
methods myself in order to guarantee full atomicity across all accessors?