Mastering In CoreData (Part 12 Multithreading Concurrency Problem)
In part 2 Core Data stack we said
Managed Object Context (MOC)
Concurrency Problem
Let’s suppose we have two managed Object Context we called Managed Object Context A and Managed Object Context B both request User data from the persistent store as shown in Figure 1. User Entity has countproperty.
Managed Object Context A private context that is processing server data
Managed Object Context B representing UI data
In the Figure 2 persistent store sends User Entity data to both the contexts
领英推荐
As shown in Figure 3 Managed Object Context A updated count value to 2 from the data that comes from server and pushed that changes to persistent Store Coordinator to Persistent Store using save() method on the context. Managed Object Context B doesn't know that changes still and still have older count value which is a problem
In part 2 Core Data stack we said
Managed Object Context (MOC)
As shown in Figure 4 since NSManagedObjectContext B is unaware of this server update . When user update value from client side when NSManagedObjectContext B tries to update value it again pushed count value to 2 which is wrong
We need multiple Managed Object Contexts if you perform Core Data operations on multiple threads. The caveat, however, is that managed object contexts are unaware of each other’s existence. Changes made to a managed object in one managed object context are not automatically propagated to other managed object contexts. How do we solve this problem?
Solution
There are two popular strategies that Core Data supports, notifications and parent-child managed object contexts