Handling multiple managedobjectcontext

114 Views Asked by At

I have three managed object context, namely :

masterManagedObjectContext(NSPrivateQueueConcurrencyType), 
backgroundMangedObjectContext(NSPrivateQueueConcurrencyType), 
uiManagedObjectContext(NSMainQueueConcurrencyType)

Master is the parent, and other two are its children. When I save any child context, I do save master context. But when backgroundMangedObjectContext saves in master, UIManagedObjectContext did not get the updated data in executeFetchRequest.

How do I achieve this? Please help. I am very much caught into this issue for past three days.

There were some posts suggest that, I must invalidate the previously fetched objects, when master gets saved. But I have no clue how to do it.

I tried

[UIManagedObjectContext reset]

But no luck.

1

There are 1 best solutions below

4
On

Try this,

You need to add observer in viewDidLoad or init method,

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification object:nil];

and implement this method,

Wherever you call this method [context save:nil], it will call automatically and changes will update to masterContext.

- (void)contextDidSave:(NSNotification *)notification
{
    SEL selector = @selector(mergeChangesFromContextDidSaveNotification:);
    [[self masterManagedObjectContext] performSelectorOnMainThread:selector withObject:notification waitUntilDone:YES];

}