Search code examples
ioscore-datansmanagedobjectcontextnsoperationqueue

How to cancel performBlock:


I implemented a search and for every new character typed by the user a performFetch: is started inside of a performBlock:. If the search string changes I would like to cancel the previous started block and start over. How would I cancel or at least inform the block inside the performBlock:about it?

Example code I have right now:

[myManagedObjectContext performBlock:^{
        // fetch from background queue
        if([[self fetchedResultsController] performFetch:nil]) {
            // update the view from the main queue
            // don't do this if performBlock already got started again! but how?
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                // refresh UI
            }];
        }
    }];

Solution

  • There is no API to cancel a performBlock. Once it starts, it continues until it completes or until your code returns from it.

    If you find it necessary to cancel fetches while they are in progress, look into NSAsynchronousFetchRequest, which allows cancellation via NSProgress. Async fetch requests and cancellation are described in the WWDC 2014 Core Data session