Merge policy in Core Data
First question how to prevent duplicate entries in core data?
Constraints, by giving constraints to our entity we can prevent duplicate entries in core data.
We can set multiple attribute by comma separated(it’s case sensitive). In my case I have set only for name attribute.
So now if you try to insert any duplicate data it will throw an error.
But what if we want to replace the existing data with the new one?
here merge policy will help here us
We have to set mergePolicy to our Persistent Container(it has responsible for executing queries on the store)
In above example if I’m trying to insert new data with same name then it’s replacing the old data with new one but it’s not inserting new data or throwing an error.
But also we have total 5 types of merge policy:
1. NSMergeByPropertyObjectTrumpMergePolicy — it takes whatever was in the object context(the data store changes will be discarded for the changed properties).
2. NSMergeByPropertyStoreTrumpMergePolicy — it takes whatever was in the store.
3. NSErrorMergePolicy — it simply returns an error for each merge conflict, and is the default.
4. NSOverwriteMergePolicy — it simply force all the changes in the object context into the data store.
5. NSRollbackMergePolicy — it discards any object context changes that conflict with what’s in the data store. If you made a changes but that changes is not stored yet so that all changes which is not stored or changed that will be discarded.
For more visit: https://ioslifee.blogspot.com
Thanks for reading, Happy Coding 💻