Search code examples
ioscore-dataconcurrencydocumentationnsoperation

Why should I create the context in main for a serial queue and in start for a concurrent queue?


There is topic about Thread Confinement pattern in Core Data programming Guide and it says that

You must create the managed context on the thread on which is will be used. If you use NSOperation, note that its init method is invoked on the same thread as the caller. You must not, therefore, create a managed object context for the queue in the queue’s init method, otherwise it is associated with the caller’s thread. Instead, you should create the context in main (for a serial queue) or start (for a concurrent queue).

I just can't get why is that? Where is the difference?


Solution

  • It says why pretty clear in the documentation that you quoted. The operations init method runs on the callers thread while the work that happens in the main method may run on another thread.

    Since you cannot share managed object contexts between threads you need to create it on the same thread as you will be using it. Thus, if you use it in the operation you need to make sure that the context is created on the same thread as the operation runs on.

    The reason why serial operations create the context in main is that they run the default start implementation while you override start when you implement concurrent operations.

    You can read more about how concurrent operations work in the Concurrency Programming Guide (tip: search for "start")