Thread-safe atomic property for array
Thread-safe atomic property for array
- Subject: Thread-safe atomic property for array
- From: Trygve Inda <email@hidden>
- Date: Fri, 14 Aug 2015 16:59:12 -0700
- Thread-topic: Thread-safe atomic property for array
My main thread periodically downloads some data from a website. This is
extracted into an NSArray (non-mutable) and placed in a property:
@property (atomic, retain) NSArray* myArray;
[self setMyArray:webArray];
Ok so far... The "atomic" ensures that the property can be set correctly
even if other threads are reading from it.
However...
I have several threads that need read-access to this array:
NSString* someString = [[hostObject myArray] objectAtIndex:2];
How can I do this safely?
The problem here is that if myArray is being replaced in the main thread
after [hostObject myArray] is called but before objectAtIndex:2 is called,
than myArray will disappear out from under the caller.
So in my thread I could do...
NSArray* arrayCopy = [[hostObject myArray] copy];
Even this could fail if the array is replaced on the main thread before the
copy method gets called.
So, how can I ensure that my threads can grab a copy of the array to work
with while allowing the main thread to update it?
It is ok if the threads copy and work with the array and the array gets
updated.. Having an old version in a thread is fine as they will get a fresh
copy the next time it runs.
I was thinking of storing this in Core Data to allow for all this using a
NSMainQueueConcurrencyType and NSPrivateQueueConcurrencyType, but it would
be simpler if I could avoid all that.
Thanks,
Trygve
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden