BYZZav
BYZZav

Reputation: 1458

Understanding nested contexts in Core Data

I have the following structure

Persistent Store <-> Parent Context <-> MOC (on Main Thread) <-> background thread MOC (MOC = Managed Object Context)

So, I'm doing some work on a background context.

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

I fetch some objects from a table and delete some of them on the 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, say I want to refetch just the remaining users into an array...

Will it refetch all the users that were originally there, or only refetch the ones that weren't deleted?

If I were to save my 'context' would it make any difference?

Basically, I'm trying to understand the difference between fetches and saves with nested contexts.

Thanks

Upvotes: 4

Views: 1269

Answers (1)

Mark Kryzhanouski
Mark Kryzhanouski

Reputation: 7241

You can refetch users in both ways by setting -[NSFetchRequest setIncludesPendingChanges] property. The default value is YES. If the value is NO, the fetch request skips checking unsaved changes and only returns objects that matched the predicate in the persistent store.

If you save child context it just only pushes your changes into parent context. And finally to see your changes in persistent store you need to save parent context. To make this you may use following code snippet :

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

Upvotes: 2

Related Questions