Understanding Nested Contexts in Master Data

I have the following structure

Persistent storage ↔ Parent context ↔ MOC (on the main topic) ↔ MOC background thread (MOC = Managed object context)

So I'm doing some work in the background context

// Create a background context. NSManagedObjectContext* context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; context.parentContext = self.document.managedObjectContext; // Start using it, but in its own thread! [context performBlock:^ {... 

I am extracting some objects from the table and deleting some of them in context.

 NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"User"]; NSArray* userQueryResults = [context executeFetchRequest:request error:&error]; for (int i = 0; i < userQueryResults.count; i++) { if(someCondition) [context deleteObject:[userQueryResults objectAtIndex:bla]; } 

Now, let's say I want to restore only the remaining users to an array ...

Will it return all users that were originally there, or only restore those that were not deleted?

If I were to keep my "context" doesn't matter?

Basically I am trying to understand the difference between selections and save with nested contexts ...

thanks

+4
source share
1 answer

You can restore users in both directions by setting the [NSFetchRequest setIncludesPendingChanges] property. The default value is YES. If the value is NO, the fetch request skips checking for unsaved changes and returns only objects that match the predicate in persistent storage.

If you save the child context, it just pushes your changes to the parent context. And finally, to see your changes in persistent storage, you need to save the parent context. You can use the following code snippet for this:

 [context performBlock:^{ NSError* error = nil; [context save:&error]; [self.document.managedObjectContext performBlock:^{ NSError* parentError = nil; [self.document.managedObjectContext save:&parentError]; }]; }]; 
+2
source

All Articles