سؤال

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