It doesn't really matter that the background thread has completed, the problem is that you can't safely use the same managed object context on multiple threads without ensuring synchronization-- possibly by using GCD calls like dispatch_async
but preferably by using Core Data's built-in synchronization system. I don't know specifically why it's failing in this case, but you're violating a major rule of safe Core Data usage, so bad results are expected.
To use Core Data's built-in syncing, create your context using NSMainQueueConcurrencyType
or NSPrivateQueueConcurrencyType
. Then, whenever you use that context (or objects that you have fetched from that context), put your code inside a performBlock
or performBlockAndWait
call. This will guarantee synchronous access regardless of the number of threads or queues.
Alternately, create a new managed object context for the background thread. There's no reason to not have more than one. Do your work on this separate context, and listen for NSManagedObjectContextDidSaveNotification
on the main thread to merge in new changes.
But whatever you do, don't use the same context on multiple threads without adequate precautions. Even when it works, it's only by chance. It'll fail eventually.