Jackson Tale
Jackson Tale

Reputation: 25842

CoreData - How to do NSFetchRequest with temporary context with NSPrivateQueueConcurrencyType?

Since iOS 5, CoreData introduces its own private queue where you can let some operations (especially save context) running in background.

This must be done via [context performBlock:...].

It is easy very good for saving the context. However, how about for NSFetchRequest? I mean what if I want to fetch something and wish to fetch in the background? I don't think [context performBlock..] can achieve this.

Is there also a new way to do so?

Upvotes: 4

Views: 596

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

Anything that involves the NSManagedObjectContext of NSPrivateQueueConcurrencyType should be wrapped in a performBlock block. For background fetching where you want to pass managed objects back to the main queue's context, something like this: (note this is just for illustrative purposes):

// assume self.managedObjectContext is a main queue context
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[backgroundContext performBlock:^{
    // do your fetch - e.g. executeFetchRequest
    NSManagedObjectID *objID = [someManagedObject objectID];
    [self.managedObjectContext performBlock:^{
        NSManagedObject *mainManagedObject = [self.managedObjectContext objectWithID:objID];
        //  do something now with this managed object in the main context
    }];
}];

Upvotes: 4

Related Questions