Question

I understand that NSMutableArray shouldn't be trusted to be thread-safe, but what if I only call [array addObject:object] and I'm not accessing the array any other way while doing so?

For example:

NSMutableArray* array = [[NSMutableArray alloc] init];
[self.subviews
  enumerateObjectsWithOptions:NSEnumerationConcurrent
  usingBlock:^(UIView* view, NSUInteger idx, BOOL *stop) {
    if ([self methodThatReturnsBool:view]) [array addObject:view];
  }];

Thanks for any advice! :)

Was it helpful?

Solution

NSMutableArray is not guaranteed to be thread-safe — not even just adding objects, because making that thread-safe would require addObject: to be an atomic operation, which is not part of the class's contract.

In general, if the documentation says "This is thread-safe," it is thread-safe (at least in isolation), but if the docs don't say that, you should assume it is unsafe and you need to use synchronization.

OTHER TIPS

As Bryan Chen pointed out, the NSEnumerationConcurrent thread will cause the block to be run on different threads "at the same time". Modifying an NSMutableArray cannot be done at the same time, from different threads.

Apple's documentation says https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-SW1 says that "In most cases, you can use these classes from any thread as long as you use them from only one thread at a time."

So, in your case, you should not do what you are trying to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top