Core Data concurrency queue style MOC getters thread safety

610 views Asked by At

I am really confused by the following paragraph straight from the NSManagedObjectContext documentation:

Setter methods on queue-based managed object contexts are thread-safe. You can invoke these methods directly on any thread.

The big question is setters methods on the ManagedObjectContext but NOT in the ManagedObjects owned by this context? or is it on both?. Specifically if for a private queue MOC object something like this:

[privateContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];

Would be thread safe regardless of the thread executing this line but would something like:

 [myPrivateQueueOwnedManagedObject setTitle:@"My Title];

Also be thread safe?, the documentation is really vague on this, but my understanding is that this would NOT be thread safe is that correct?

What about getters for properties in the ManagedObjectContext such as asking for the persistentStoreCoordinator property would that be thread safe?. My Understanding is that it would not be.

Additionally it has always been my understanding that certain Managed Object properties such as objectID are thread safe and do not need to be accessed using performBlock: or performBlockAndWait: are there any other properties on the Managed Object that are thread safe?

1

There are 1 answers

2
Marcus S. Zarra On BEST ANSWER

-setPersistentStoreCoordinator: is thread safe as it is a setter method on the managed object context.

-setTitle: is not because you are calling a setter on a managed object.

You can confirm this behavior by using the debug flag:

-com.apple.CoreData.ConcurrencyDebug 1

Which will throw an assertion when you violate thread confinement.

Update

While we are at it just to confirm the second paragraph on the documentation, is it safe to access BOTH MOC and MO for main style queue MOC objects while on the main thread?. my understanding is that it is so for instance setTitle would be ok if the context was Main style and the thread was the main thread. This is for legacy reasons with thread confinement afaik, and also a great help when using the MO for UI updates.

If the context as defined as main queue and you are on the main queue (aka UI thread, aka main thread) then yes you can access everything directly without a -performBlock:. You are on the thread that the context belongs to so you are following the thread confinement rules.