iOS-串联基于异步块的操作 [英] iOS - Concatenating asynchronous block-based operations

查看:110
本文介绍了iOS-串联基于异步块的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何执行N个异步操作,例如网络调用,使用完成块操作并且没有委托/通知?

How would you perform N asynchronous operations, such as network calls, working with completion block operations and no delegates/notifications?

给出N个这样的方法:

- (void)methodNWithCompletion:(void (^)(Result *))completion {
    Operation *operation = [Operation new];

    // ...
    // Asynchronous operation performed here
    // ...

    return;
}

一种直接的解决方案是在上一个操作的完成代码块中调用每个操作:

A straightforward solution would be to call each operation in the completion block of the previous one:

[self method1WithCompletion:^(Result *result) {
    // ...
    [self method2WithCompletion:^(Result *result) {
        // ...
        [self method3WithCompletion:^(Result *result) {
            // ...
            [self method4WithCompletion:^(Result *result) {
                NSLog(@"All done");
            }
        }
    }
}

但是我正在寻找一种更优雅,更可重用的解决方案,更易于编写和维护(没有很多缩进块).

but I'm looking for a more elegant and reusable solution, easier to write and maintain (with no many indented blocks).

非常感谢, 丹

推荐答案

这完全取决于您要执行的操作.您可以使用许多强大的复杂工具.您可以使用以下内容:

It all depends on what you want to do. Many powerful sophisticated tools are at your disposal. You can use such things as:

  • 串行队列(如果您希望按顺序运行完成块)

  • Serial queue (if you want the completion blocks run in order)

并发队列(如果您不关心完成块是同时执行还是以什么顺序执行)

Concurrent queue (if you don't care whether the completion blocks execute simultaneously or in what order)

调度组(如果只有在所有完成块都完成后才想做的事情)

Dispatch group (if there is something you want to do only after all completion blocks have finished)

Operation and OperationQueue(如果要建立必须进行网络操作的依赖关系顺序,请参阅关于此主题的esp.精彩的WWDC 2015视频)

Operation and OperationQueue (if you want to establish the dependency order in which networking operations must take place - see esp. the fantastic WWDC 2015 video on this topic)

这篇关于iOS-串联基于异步块的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆