How do I reconcile Core Data conflicts from multiple devices?

When working with Core Data across multiple devices, resolving conflicts is crucial to maintain data integrity. Conflicts can occur when two devices attempt to modify the same data simultaneously. Here’s how to effectively reconcile those conflicts:

  1. Use Merge Policies: Define a merge policy for your Core Data stack to handle conflicts. Common options are NSMergeByPropertyObjectTrumpMergePolicy or NSMergeByPropertyStoreTrumpMergePolicy.
  2. Handle Conflicts in Save: Override the save() method to catch and handle conflicts.
  3. Custom Conflict Resolution: Implement a custom approach by checking timestamps or version numbers to decide which changes to keep.

Here’s an example of how to set a merge policy and handle a conflict:

// Set Merge Policy let context = persistentContainer.viewContext context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy // Save Context with Conflict Handling do { try context.save() } catch { if let nsError = error as NSError? { // Handle conflict print("Conflict with \(nsError)") context.rollback() } }

Core Data conflict resolution multiple devices merge policies data integrity