Objective-C – 等待两个异步方法完成

前端之家收集整理的这篇文章主要介绍了Objective-C – 等待两个异步方法完成前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在调用我想以同步顺序执行的四个方法,前两个方法是同步的,后两个方法是异步的(从URL获取数据).

代码

- (void)syncData {

    // Show activity indicator
    [object sync]; // Synchronous method
    [object2 sync]; // Synchronous method
    BOOL object3Synced = [object3 sync]; // Async method
    BOOL object4Synced = [object4 sync]; // Async method
    // Wait for object3 and object4 has finished and then hide activity indicator
}

我怎样才能做到这一点?

解决方法

假设你实际上有某种方式知道异步方法何时完成,你可能想要的是:
- (void)syncData {

    // Show activity indicator
    [object sync]; // Synchronous method
    [object2 sync]; // Synchronous method

    _object3Synced = _object4Synced = NO;
    [object3 syncWithCompletionHandler:
          ^{
               _object3Synced = YES;
               [self considerHidingActivityIndicator];
          }]; // Async method
    [object4 syncWithCompletionHandler:
          ^{
               _object4Synced = YES;
               [self considerHidingActivityIndicator];
          }]; // Async method
}

- (void)considerHidingActivityIndicator
{
     if(_object3Synced && _object4Synced)
     {
         // hide activity indicator,etc
     }
}
原文链接:https://www.f2er.com/c/117712.html

猜你在找的C&C++相关文章