0

我正在使用NSOperation来执行两个操作。第一个操作是从Internet加载数据,而第二个操作是更新UI。如何真正取消操作

但是,如果viewDidDisappear函数是由用户触发的,我该如何停止数据加载过程? 我试图

[taskQueue cancellAllOperations], 

不过这个功能只作为抵消,而不是字面上取消执行过程中标志着一切操作。

任何人都可以请提出一些建议吗?提前致谢。

回答

0

非常感谢您的回答。但我发现其实

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

解决我的问题。该过程不必取消。感觉像NSOpertaions不在后台运行。因此,当nsoperation仍在运行时返回到超级导航视图,UI将会卡住!

0

AFAIK,没有直接的方法来取消已经执行的NSOperation。但是你可以像你在做的那样取消taskQueue

[taskQueue cancellAllOperations]; 

和操作块,周期性地(在代码逻辑原子块之间)检查isCancelled,以决定是否继续进行内部。

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 
    } 
}]; 

NSOperation的块应仔细划分为子块,这样,它是安全的停止块的其余部分的执行。如果需要,您还应该回滚到目前为止执行的子块的效果。

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

感谢您的回复。对我有意义。 – xpeng