I suffered all the consequences of using a single MOC in multiple threads - my app crashes at random points because the MOC is created in the main thread and I also use it t
Use one NSManagedObjectContext
per thread. If you communicate between threads, pass the NSManagedObjectID
, which is thread safe, and fetch the object again from you thread context. In my apps I sometimes even use one context per controller.
To manage the different contexts, register an Observer for the NSManagedObjectContextDidChangeNotification
. Within this notification handling, you pass the notification to each of your contexts via the mergeChangesFromContextDidSaveNotification:
method. This method is thread save and makes the context update its state.
After this you have to refresh your views. If you have a table view based application, have a look at NSFetchedResultsController
. This helps you update the table automatically with appropriate animations. If you don't use table views, you have to implement the UI update yourself.
If you are only supporting iOS 5 and above you don't need to deal with NSManagedObjectID
and merging contexts anymore. You can use the new concurrency types of NSManagedObjectContext
instead. Then do your operations within managedObjectContext:performBlock
and they will be merged automatically.
See the answer from svena here for more information: Core Data and Concurrency using NSOperationQueues