gpt4 book ai didi

ios - 异步 block 的推荐设计模式?

转载 作者:可可西里 更新时间:2023-11-01 03:55:12 25 4
gpt4 key购买 nike

我正在开发一个具有高度异步设计的 iOS 应用程序。在某些情况下,单个概念性“操作”可能会将许多子 block 排队,这些子 block 将异步执行并异步接收它们的响应(对远程服务器的调用)。这些子 block 中的任何一个都可能在错误状态下完成执行。如果任何子 block 中发生错误,则应取消任何其他子 block ,错误状态应向上渗透到父 block ,并应执行父 block 的错误处理 block 。

我想知道在这样的环境中可以推荐哪些设计模式和其他技巧?

我知道 GCD 的 dispatch_group_async 和 dispatch_group_wait 功能。这可能是此应用程序设计中的一个缺陷,但我对 dispatch_group_async 的运气并不好,因为该组似乎对子 block 没有“粘性”。

提前致谢!

最佳答案

有一个 WWDC 视频 (2012) 可能会帮助您。它使用自定义 NSOperationQueue 并将异步 block 放在 NSOperations 中,这样您就可以控制 block 并取消剩余的排队 block 。

一个想法是让子 block 的错误处理在处理 NSOperationQueue 的类的主线程上调用一个方法。然后类(class)可以适当取消其余部分。这样子 block 只需要知道自己的线程和主线程。这是视频的链接

https://developer.apple.com/videos/wwdc/2012/

该视频名为“在 iOS 上构建并发用户界面”。相关部分主要在后半部分,但您可能想要观看整个内容,因为它很好地结合了上下文。

编辑:

如果可能,我建议在嵌入式 block 中处理响应,将响应很好地包装在一起,这就是我认为您所追求的......

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

关于ios - 异步 block 的推荐设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com