1

In my iOS app I have a Managed Object Context for the background thread, and the main thread. The problem is that my core data call to get a certain entity can take about 3-5 seconds and would be horrible to keep on the main thread but when I put it on the background thread on a separate Managed Object Context just for retrieving data on the background thread that is just for retrieving data in the background I get deadlocks.

My question is: Is there a way that I can use multiple Managed Object Contexts in the background thread? Should what I am doing right now work and I am just doing something wrong somewhere like passing objects between contexts (I have checked for that I didn't see anything)?

harryisaac
  • 1,121
  • 1
  • 10
  • 18

1 Answers1

3

Managed object contexts are not thread safe so if you ever need to do any kind of background work with your Coredata objects (i.e. a long running import/export function without blocking the main UI) you will want to do that on a background thread.

In these cases you will need to create a new managed object context on the background thread, iterate through your coredata operation and then notify the main context of your changes.

See Example Here

Apple Documentation:

Use Thread Confinement to Support Concurrency

The pattern recommended for concurrent programming with Core Data is thread confinement: each thread must have its own entirely private managed object context.

There are two possible ways to adopt the pattern:

Create a separate managed object context for each thread and share a single persistent store coordinator. This is the typically-recommended approach.

Create a separate managed object context and persistent store coordinator for each thread. This approach provides for greater concurrency at the expense of greater complexity (particularly if you need to communicate changes between different contexts) and increased memory usage.

Community
  • 1
  • 1
Abhinav
  • 37,684
  • 43
  • 191
  • 309
  • I understand that and I am already doing that but the problem is that I need to do not only editing data in the background but also retrieving so what I want to know is wether it is possible to have multiple managed object contexts on a thread? – harryisaac Nov 09 '13 at 00:31
  • As per apple guidelines you should create one MOC per thread. You can use the same MOC for multiple purposes. Also, never cross thread boundaries as far as MOC creation and usage is concerned. Edited my answer with some Apple Documentation. – Abhinav Nov 09 '13 at 00:39
  • Ok, but isn't it a problem to be saving and retrieving data on the same Managed Object Context at the same time? – harryisaac Nov 09 '13 at 01:55