0

I'm using NSOperation to perform two operations. The first operation is loading the data from Internet, while the second operation is updating the UI.

However, if the viewDidDisappear function is triggered by user, how can I stop the data loading process? I tried

[taskQueue cancellAllOperations], 

but this function only marks every operation inside as cancelled while not literally cancel the executing process.

Could anyone please give some suggestions? Thanks in Advance.

xpeng
  • 23
  • 4

2 Answers2

0

AFAIK, there's no direct way to cancel an already executing NSOperation. But you can cancel the taskQueue like you're doing.

[taskQueue cancellAllOperations];

And inside the operation block, periodically (in between logically atomic block of code) check for isCancelled to decide whether to proceed further.

NSBlockOperation *loadOp = [[NSBlockOperation alloc]init];
__weak NSBlockOperation *weakRefToLoadOp = loadOp;

[loadOp addExecutionBlock:^{
    if (!weakRefToLoadOp.cancelled) {
        // some atomic block of code 1
    }
    if (!weakRefToLoadOp.cancelled) {
        // some atomic block of code 2
    }
    if (!weakRefToLoadOp.cancelled) {
        // some atomic block of code 3
    }
}];

The NSOperation's block should be carefully divided into sub-block, such that it is safe to discontinue the execution of rest of the block. If required, you should also rollback the effects of sub-blocks executed so far.

    if (!weakRefToLoadOp.cancelled) {
        // nth sub-block
    }
    else {
        //handle the effects of so-far-executed (n-1) sub-blocks
    }
0

Thanks sincerely for your answer. But I find out that actually

[self performSelectorInBackground:@selector(httpRetrieve) withObject:nil];

solve my problem. The process don't have to be cancelled. And feels like NSOpertaions is not running in the background. Thus, back to super navigation view while the nsoperation is still running, the UI will become stuck!

xpeng
  • 23
  • 4