Search code examples
iosmultithreadingcore-datadeadlocknsmanagedobjectcontext

Solve a Core Data deadlock that happens occasionally when a table view is being loaded


I am using a pretty common Core Data Stack. Child Mocs -> Main Moc -> Background Moc -> PSC

I have been facing a Core Data Deadlock from quite some time now wherein when i tap on a cell of my table view to open another table view, the screen would freeze, both my table views use FRC. Looking at the threads it looks like my all 3 Managed Object Contexts are in a deadlock state. I have tried to debug it multiple times now but to no avail.

Thread 1 : Main Moc

Thread 8 : Child Moc

Thread 10 : Background Moc

Any help would be greatly appreciated.

Main Thread(1/2)

Main Thread(2/2)

Thread 8:Child Moc, Thread 10:Background Moc


Solution

  • I figured that the issue was happening when there was concurrent access to different persistent stores (2 in my case). The first persistent store was accessed via Background Moc and at the same time there was a fetch request flowing via Child Moc concerned with the second persistent store.

    I refrained from making the first fetch request in question from the Background Moc and moved it to one of the Child Mocs and the deadlock was resolved.

    I still do not know the exact cause but i was able to get this workaround.

    Hope this helps.