Search code examples
swiftmultithreadingcore-datansmanagedobjectnsmanagedobjectcontext

Syncing data to server in a background thread: multiple-contexts in core data


I have two NSManagedObjectContext : parentContext which is the main context and a childContext with PrivateQueueConcurrencyType. Using the childContext I am syncing data to the server in a background thread and after the sync succeeds I set data.isSynced = true.

The user might change the data during the sync. This will mark the data as dirty by setting data.isSynced = false.

Both threads (main and syncing) are running concurrently and a bad scenario can happen here if the parentContext has data.isSynced == false and the childContext has data.isSynced == true. Calling the childContext.save() will override changes in the parentContext and I will miss the changes and won't sync again the updated data to the server.

How can I improve the current design? Is there a way to customize the merge between the parent and child contexts?


Solution

  • Don't use a single bool flag, use 2 dates instead. One date is for the last edit and the other is for the last sync. They are each only ever updated from 1 thread. The background thread will read both to check if data needs to be synced but that's fine.