有一个 WWDC 视频 (2012) 可能会对您有所帮助。它使用自定义NSOperationQueue
并将异步块放置在内部NSOperations
,因此您可以保留块的句柄并取消剩余的排队块。
一个想法是让子块的错误处理在处理NSOperationQueue
. 然后班级可以适当地取消其余部分。这样子块只需要知道自己的线程和主线程。这是视频的链接
https://developer.apple.com/videos/wwdc/2012/
该视频名为“在 iOS 上构建并发用户界面”。相关部分主要是在后半部分,但你可能会想看整个事情,因为它很好地结合了上下文。
编辑:
如果可能的话,我建议在嵌入块中处理响应,它将它很好地包装在一起,这就是我认为你所追求的......
//Define an NSBlockOperation, and get weak reference to it
NSBlockOperation *blockOp = [[NSBlockOperation alloc]init];
__weak NSBlockOperation *weakBlockOp = blockOp;
//Define the block and add to the NSOperationQueue, when the view controller is popped
//we can call -[NSOperationQueue cancelAllOperations] which will cancel all pending threaded ops
[blockOp addExecutionBlock: ^{
//Once a block is executing, will need to put manual checks to see if cancel flag has been set otherwise
//the operation will not be cancelled. The check is rather pointless in this example, but if the
//block contained multiple lines of long running code it would make sense to do this at safe points
if (![weakBlockOp isCancelled]) {
//substitute code in here, possibly use *synchronous* NSURLConnection to get
//what you need. This code will block the thread until the server response
//completes. Hence not executing the following block and keeping it on the
//queue.
__block NSData *temp;
response = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
[operationQueue addOperationWithBlock:^{
if (error) {
dispatch_async(dispatch_get_main_queue(), ^{
//Call selector on main thread to handle canceling
//Main thread can then use handle on NSOperationQueue
//to cancel the rest of the blocks
});
else {
//Continue executing relevant code....
}
}];
}
}];
[operationQueue addOperation:blockOp];