On Aug 12, 2013, at 11:23 AM, Koen van der Drift <[email protected]> 
wrote:

> 
> On Aug 12, 2013, at 2:05 PM, Jens Alfke <[email protected]> wrote:
> 
>> NSMutableArray isn’t thread-safe. You’ll need to synchronize/serialize the 
>> assignments somehow. You could do something like
>> 
>> {
>>      id value = [self doCalculation: i];
>>      @synchronized(myArray) {
>>              myArray[i] = value;
>>      }
>> }
>> 
> 
> Unfortunately, I'm still getting the same error.

I suspect there’s an additional complication. In your single-threaded case you 
probably assumed that `i` increased uniformly and monotonically, so that 
myArray[i] = foo always appended objects to the array. In a multithreaded 
implementation this is no longer the case: there’s a race between different 
values of `i`, so it’s entirely possible that you will try to, say, set the 
object at index 3 before index 2. This will raise a range exception as you are 
seeing.

There are at least two possible fixes.

First, since you know the array size in advance, you could do something like 
pre-fill myArray with [NSNull null]. This would work around the range exception 
by having your code replace objects rather than append new objects.

Second, you could switch from an array to an order-agnostic collection such as 
a dictionary or set. NSPointerArray may also provide useful behavior.

Exactly which approach you take will depend on specifics about your application 
and the problem you are solving.

-Conrad
_______________________________________________

Cocoa-dev mailing list ([email protected])

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to