Domanda

I am inside a method with a code like this

  __block NSMutableArray *myArray = [[NSMutableArray alloc] init];

  [anotherArray enumerateObjectsWithOptions:NSEnumerationConcurrent
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

     // do some calculation and generate an object
     [myArray addObject:anObject];


  }];

because the enumeration is concurrent, I have a crash when several threads try to add objects to myArray.

I know about atomic properties but I wonder if there is a way of making myArray atomic and thread safe without using a property. I want to keep it local.

È stato utile?

Soluzione

old C array may help

id array[anotherArray.count];
id __strong *arrayPtr = array;

  [anotherArray enumerateObjectsWithOptions:NSEnumerationConcurrent
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

     // do some calculation and generate an object
     arrayPtr[idx] = anObject;

  }];

 NSMutableArray *myArray = [NSMutableArray arrayWithObjects:array count:anotherArray.count];

Altri suggerimenti

Since you need serial access to myArray, using a concurrent enumeration may be pointless. But it may depend on what you do in the enumeration besides adding the object to the array.

You can synchronize access to the array:

@synchronized(myArray) {
    [myArray addObject:anObject];
}

It would be interesting to run some performance tests to see if doing the above is actually slower than simply using a serial enumeration since you then wouldn't need the overhead of synchronizing the array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top