Reputation: 35953
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.
Upvotes: 1
Views: 694
Reputation: 46598
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];
Upvotes: 3
Reputation: 318814
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.
Upvotes: 3