views:

43

answers:

2

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?

+3  A: 

The Objective-C docs at developer.apple.com[1] don't state that there's a way to use the same lock for your explicitly defined functions as gets used for your @synthesized functions. In that case I'd say that to be completely safe it would be better to fully define your own functions to be sure they all use the same lock.

You may be able to use the debugger to determine the name of the lock that gets used for your @synthesized functions, but that's not something I'd rely on.

alesplin
A: 

You probably don't really want to do this. If you do succeed, KVO-notifications will be received on the same thread that makes the change, and if it's a background thread, will be unsuitable for updating the UI.

Instead, why not have your background thread update the property using the main thread? Then you don't even need the property to be atomic.

Mike Abdullah