我正在调用我想以同步顺序执行的四个方法,前两个方法是同步的,后两个方法是异步的(从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 } }