In order to avoid race conditions around Core Data, different threads should use different NSManagedObjectContext
s (see e.g. here).
To ensure this at runtime I would like to assert before each use of a managed object context that the same thread (or operation queue) is current as was when the managed object context was created. In effect, I would like to assert something like NSThread.currentThread == storedThread
(or NSOperationQueue.currentQueue == storedQueue
).
Is it appropriate to check for pointer equality between threads (or operation queues) for the stated purpose? And is there a semantic difference between comparing threads and operation queues, again for this stated purpose? (The Apple documentation for frameworks such as Core Data and UIKit usually explains situations around race conditions in terms of threads, e.g.: "Create a separate managed object context for each thread and share a single persistent store coordinator.")
UPDATE I've by now learned (from revisiting WWDC 2012 Session 2014 Core Data Best Practices) that using a NSManagedObjectContext
with NSPrivateThreadConcurrencyType
will probably solve this and is the way to go. However, the question would still seem to apply to the legacy choice NSConfinedConcurrencyType
.
UPDATE From the WWDC 2014 session on What's new in Core Data: the launch argument -com.apple.CoreData.ConcurrencyDebug 1
is by now also supported on iOS and implies pretty much the same assertions that I was aiming at (see here).
Relying on Core Data's own assertions turned out to be the way to go (see updated question). By relying on the I no longer need to compare for equality of threads (or other abstractions of "threads") at the application level.