4

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?

Jackson Tale
  • 25,428
  • 34
  • 149
  • 271

1 Answers1

4

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
    }];
}];
FluffulousChimp
  • 9,157
  • 3
  • 35
  • 42