Search code examples
objective-ccore-datansmanagedobjectcontext

Cancelling NSManagedObjectContext performBlock


I am using parent/child concurrency pattern to import large data chunks. Importing is performed in the background without blocking the main thread, like this:

NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
temporaryContext.parentContext = mainMOC;

[temporaryContext performBlock:^{
   // import data …

   // push to parent
   NSError *error;
   if (![temporaryContext save:&error]) {
      // handle error
   }

   // save parent to disk asynchronously
   [mainMOC performBlock:^{
      NSError *error;
      if (![mainMOC save:&error]) {
         // handle error
      }
   }];
}];

Everything works great, but what if I need to cancel data import? Is there any way to cancel performBlock?


Solution

  • No - blocks and other any synchronous operation can not implicitly be cancelled.

    you have to program it to be cancellable

    e.g. here maybe... split the performBLock up into N calls That each only do little work.