johnMa
johnMa

Reputation: 3311

Core Data with Nested PerformBlock

I've read some articles and still don't reach a conclusion. Let's say I have a nested NSManagedObjectContext like

 BackgroundContext -> NSPrivateQueueConcurrencyType
              | 
            child
              v
 MianContext -> NSMainQueueConcurrencyType
              |
            child
              v
 TemporaryContext -> NSPrivateQueueConcurrencyType

Question 1: Should I still observe NSManagedObjectContextObjectsDidChangeNotification and merge changes like :

- (void)managedObjectContextDidChanged:(NSNotification *)notification{
    NSManagedObjectContext *currentContext = [notification object];
    NSManagedObjectContext *mainConetext = [self mainThreadContext];
    if (currentContext != mainConetext) {
        [mainConetext performBlock:^{  //performBlock in notification
            [mainConetext mergeChangesFromContextDidSaveNotification:notification];
        }];
    }
}

In fact I have tried removing this code and it performs well when I perform fetches on the mainContext, but what I am confused about is How the mainContext merge the child context changes,because I feel that I'm doing something wrong here.

Question 2: Should I use nested performBlock to merge changes??

[temporaryContext performBlock:^(
    //do some thing
    [mainContext performBlock:^(
         // merge changes
    )];
)];

Upvotes: 1

Views: 445

Answers (1)

jrturton
jrturton

Reputation: 119242

When the child context is saved, those changes are automatically pushed to the parent. As it says in the docs, you can think of the stack of contexts as having a persistent store coordinator at the very root. Saved changes are pushed one level up:

When you save changes in a context, the changes are only committed “one store up.” If you save a child context, changes are pushed to its parent. Changes are not saved to the persistent store until the root context is saved. (A root managed object context is one whose parent context is nil.) In addition, a parent does not pull changes from children before it saves. You must save a child context if you want ultimately to commit the changes.

So, if you save your child context, those changes are pushed to the parent - but will not be written to disk unless the root context is saved, which for your purposes can be on a different schedule.

Merging changes and observing saves is not necessary under this structure. That's one of it's many advantages.

Upvotes: 3

Related Questions