iOS - Concatenating asynchronous block-based operations

淺唱寂寞╮ 提交于 2019-12-12 04:13:19

问题


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

Given N methods like this:

- (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).

Many thanks, DAN


回答1:


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 (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)



来源:https://stackoverflow.com/questions/40333640/ios-concatenating-asynchronous-block-based-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!