Search code examples
iosswiftcore-data

What parent is viewContext referring to, when viewContext.automaticallyMergesChangesFromParent set to true?


It is common to have background context to perform write operation.

// Set automaticallyMergesChangesFromParent to true
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
persistentContainer.performBackgroundTask { backgroundcontext in
    // Do your work...
    let object = backgroundContext.object(with: restaurant.objectID)
    backgroundContext.delete(object)
    // Save changes to persistent store, update viewContext and notify fetched results controller
    try? backgroundContext.save()
}

I am confused on the automaticallyMergesChangesFromParent.

As, I have the following observation on viewContext (The managed object context associated with the main queue) and backgroundContext.

  1. viewContext.parent is nil
  2. backgroundContext.parent is nil

My questions are

  1. If we need to set viewContext.automaticallyMergesChangesFromParent = true, in order for viewContext to receive changes from backgroundContext, does that mean backgroundContext is the parent of viewContext?
  2. If not, what parent is viewContext.automaticallyMergesChangesFromParent = true referring to?

Solution

  • If the parent is nil, it's nil, there's no implicit parent relationship. When the parent context is nil, automaticallyMergesChangesFromParent automatically merges changes saved to its persistent store coordinator. It's not a parent context but it does some parent context-like things here. As long as the two contexts use the same persistent store coordinator (or the same NSPersistentContainer) then this will automatically merge changes without a parent context relationship.