CoreData - How to execute NSFetchRequest with a temporary context using NSPrivateQueueConcurrencyType?

Starting with iOS 5, CoreData introduces its own private queue , where you can let some operations ( especially save context ) work in the background.

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

This is very convenient for saving the context . However, what about NSFetchRequest ? I mean, what if I want to bring something and want to get in the background? I do not think that [context performBlock ..] can achieve this.

Is there a new way to do this?

+4
source share
1 answer

Everything related to the NSManagedObjectContext of NSPrivateQueueConcurrencyType must be wrapped in a performBlock . To get a background fetch where you want to pass the managed objects back to the main queue context, something like this: (note this is for illustrative purposes only):

 // assume self.managedObjectContext is a main queue context NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; [backgroundContext performBlock:^{ // do your fetch - eg 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 }]; }]; 
+4
source

Source: https://habr.com/ru/post/1433678/


All Articles