When you get an error during a context save, you may have a merge conflict between the context and the persistent store. If you update your context before the save by refreshAllObjects()
, refresh(_ object:mergeChanges:)
is called for every object in the context, where mergeChanges
: is true
. This means that attributes changed in the context are kept while attributes changed in the persistent store are updated. This is exactly what is done automatically, if you set context.mergePolicy
to NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType
, see the docs here and here.
But this maybe not what you want. Consider a situation where an entity with an attribute updatedAt
can be changed locally and remotely, and the requirement is that individual attributes may not be mixed, but only the complete entity that has been updated last should be kept. In this case, none of the predefined merge policies apply, and one has to set up a custom merge policy that checks the updatedAt
attribute. How this can be done is described here.