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?

有帮助吗?

解决方案

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.

其他提示

If anyone else has the same problem my solution was to use two independent managed object contexts which are both connected to the same persistent store coordinator. The managed object context that does the heavy lifting is encapsulated in a NSOperation subclass. NSOperation can be canceled at any point. Here is a link to the example provided by Apple.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top