Re: Thread-safe atomic property for array
Re: Thread-safe atomic property for array
- Subject: Re: Thread-safe atomic property for array
- From: Mike Abdullah <email@hidden>
- Date: Sat, 15 Aug 2015 12:14:22 +0100
> On 15 Aug 2015, at 00:59, Trygve Inda <email@hidden> wrote:
>
> 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 above is ok, in that the array you’re working with will always be valid. Atomic properties guarantee that. BUT the above code will break under the circumstance that the array changes to have fewer than 3 objects.
I’m sure you check the count earlier in your code in order to know what to do, but you’ve got a race condition where the count could go down in between the check and the access. Instead, simply do:
NSArray *array = [hostObject myArray];
// run your checks, etc.
NSString *someString = [array objectAtIndex:2];
Assuming nothing in your codebase is bad-mannered enough to try and modify an array after passing it to -setMyArray: then you’ve protected yourself; the count isn’t going to change underneath you.
_______________________________________________
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