6rod9
6rod9

Reputation: 1457

Core-Data: Parent context changes not being merged into child context

My situation is: I have a multi-threaded app with core-data database, managing multiple contexts. In my context Hieratchy I have a Root Saving Context, and child contexts where I fetch data and make/save changes.

Context B is used to fetch data and be displayed in a View Controller's view.

Context C is used to save changes in a background thread.

The problem is that when I make changes in context C, save context C and A, the changes are not propagated, or merged, into context B. The changes are correctly persisted in context A and C, but not in B.

I thought that the default behaviour would be that the changes in a parent context A would be propagated into it's child context B, but it's not happening. What would be the correct way to achieve this?

Upvotes: 7

Views: 2665

Answers (1)

nils
nils

Reputation: 1976

If you are working on an iOS 10 project you can try setting the automaticallyMergesChangesFromParent property on Context B to true.

For older projects you have to merge changes yourself:

  • Observe the NSManagedObjectContextDidSave notification. Make sure to use Context C as the object when subscribing. Otherwise you will receive notifications from any context that has been saved, not just from Context C.
  • Use NSManagedObjectContext.mergeChanges(fromContextDidSave:) to update Context B. The Objective-C selector is -mergeChangesFromContextDidSaveNotification:

Upvotes: 11

Related Questions