CoreData mergeChanges

Viewed 1022

In my old projects, I've set up a Core Data store and model. In this model, I'm using a NotificationCenter to observe the NSManagedObjectContext. Whenever a context is being saved, it merges with the other contexts:

NotificationCenter.default.addObserver(self, selector: #selector(didSaveContext), name: .NSManagedObjectContextDidSave, object: nil)

@objc func didSaveContext(notification: Notification) {
    guard let sender = notification.object as? NSManagedObjectContext else { return }

    if sender === mainContext {
        userContext.perform { self.userContext.mergeChanges(fromContextDidSave: notification) }
        idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
    } else if sender === userContext {
        mainContext.perform { self.mainContext.mergeChanges(fromContextDidSave: notification) }
        idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
    } else if sender === idleContext {
        mainContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
        userContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
    } else {
        userContext.perform { self.userContext.mergeChanges(fromContextDidSave: notification) }
        mainContext.perform { self.mainContext.mergeChanges(fromContextDidSave: notification) }
        idleContext.perform { self.idleContext.mergeChanges(fromContextDidSave: notification) }
    }
}

But since iOS10, Apple introduced the NSPersistentContainer and I'm able to use:

persistentContainer.viewContext.automaticallyMergesChangesFromParent = true

Does this mean I don't have to use the notification center to merge the changes anymore?

1 Answers

Does this mean I don't have to use the notification center to merge the changes anymore?

NO, you must implement notification and call mergeChanges() to merge changes.

Related