Mastering In CoreData (Part 11 Multithreading Concurrency Rules)

Core Data

Concurrency in Core Data

Core Data, Multithreading, and the Main Thread

NSMainQueueConcurrencyType

NSPrivateQueueConcurrencyType

What managed object context was used in Parts

let managedObjectContext = appDelegate.persistentContainer.viewContext
Figure 1
  1. Managed object contexts are bound to the thread (queue) that they are associated with upon initialization
  2. Managed objects retrieved from a context are bound to the same queue that the context is bound to

Rule 1

Figure 2
Figure 3
  1. First created a context on main thread / main queue (NSMainQueueConcurrencyType) by using Persistent Container viewContext property which creates context on main thread
  2. Created another thread using DispatchQueue method and it will switch the thread
  3. We accessed main queue context on the background thread . At that time debugger will stop the application and telling that you are using context on different thread. If I disable the debugging configuration it will work but there are some scenario in which it will cause a problem. As I said earlier if you follow the rule then threading will be easy for you otherwise you will get random crashes. So to be good citizen you follow the rule “Context created on thread 1 always access this context in that thread
Figure 4

Solution

  1. Created context on main thread as we did earlier
  2. Somehow change the thread using DispatchQueue as we did earlier
  3. Used perform(_:) we used to ensure the block operations are executed on the queue specified for the context. Since the context was created on main thread perform(_:) will change the thread to main thread. You can use performAndWait(_:) method also
  4. Now In the perform(_:) block all expression will execute on main thread. Since it first check the context thread and irrespective of the current thread it will change the thread
Figure 5

Summary Rule 1

Rule 2

Figure 6
Figure 7
Figure 8
  1. Created a NSMangedObjectContext on main thread using persistent container viewContext property
  2. Created another NSManagedObjectContext on background thread using persistent container newBackgroundContext() method which will give context using concurrency type NSPrivateQueueConcurrencyType.
  3. Created User Object on main thread context
  4. Created task object on private thread context
  5. When we assign task to user object exception raised as shown in FIgure 9 and 10
Figure 9
Figure 10
Figure 11

Solution

Summary

What Next?

Useful Links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ali Akhtar

Ali Akhtar

Senior iOS Engineer | HungerStation | Delivery Hero