How to set merge policy in Swift 4 CoreData
You can put mergePolicy when initiate persistentContainer
var persistentContainer: NSPersistentContainer = {
let modelURL = Bundle.main.url(forResource: DB_NAME, withExtension: "momd")!
let container = NSPersistentContainer.init(name: DB_NAME, managedObjectModel: NSManagedObjectModel(contentsOf: modelURL)!)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
if let error = error as NSError? {
QiscusLogger.errorPrint("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
I found the answer - to set the context's merge policy, you simply do
context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
I was getting tripped up by trying to do
context.mergePolicy = mergeByPropertyObjectTrumpMergePolicyType)
but I guess it's necessary to spawn an NSMergePolicy
object. I just assumed that the actual merge policy (mergeByPropertyObjectTrumpMergePolicyType
) would be of the correct type by default.