Prevent NSManagedObjectContextDidSaveNotification event to overlap

716 views Asked by At

Ok I have a very tricky problem that I spent days to understand and know I'm not sure how to fix it.

I have a CoreData database updated from different thread with different context. My problem is that sometimes NSManagedObjectContextDidSaveNotification event overlap and create corruption of the base that lead to crash. Here is an example:

Thread                   Main                                          NSFetchResultsController

Update database
Save database           NSManagedObjectContextDidSaveNotification1
                        merge                                          delegate process 1
                                                                       process 1 done

Update database
Save database           NSManagedObjectContextDidSaveNotification2
                        merge                                          delegate process 2
                                                                       process 2 done
Update database
Save database           NSManagedObjectContextDidSaveNotification3
                        merge                                          delegate process 3

Update database
Save database           NSManagedObjectContextDidSaveNotification4
                        merge          

                                                                       process 3 done
                                                                       delegate process 4
                                                                       CRASH
                                                                       process 4 done

In this pseudo code example process1 and process2 works without problem but sometimes the main thread receives overlapping update event and the you have process4 starting to read the database before process3 is done.

Is there an official way to deal with that ? Does CoreData offers a solution to this situation or do I have to use NSLock ?

Thanks

1

There are 1 answers

2
paulbailey On

The contexts should be locking the persistent store coordinator that they share to prevent these issues.

If process 3 and process 4 are running on the main thread, then how can 4 start before 3 is finished? Don't forget that notifications are received on the thread that posts them, so you need explicitly execute your code to merge the changes on the main thread (apologies if I'm stating the obvious).