7

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 A -> Root parent context
  • Context B -> Child context of A
  • Context C -> Child context of A

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?

6rod9
  • 1,407
  • 12
  • 29

1 Answers1

11

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:
nils
  • 1,786
  • 13
  • 18
  • Just found out about `automaticallyMergesChangesFromParent`, and that the default is `NO`. solved my problem:) . By the way, the solution for iOS previous than 10 resulted useful! – 6rod9 Mar 28 '17 at 15:49
  • 2
    NB! Note that "automaticallyMergesChangesFromParent" does not merge changes immediately after calling save on the parent context. There is a slight delay. If you need the changes merged immediately, also use the "[context refreshObject:mergeChanges]" method. – RunLoop Jan 06 '20 at 07:06