对于具有ASync的循环,然后等待它完成(Obj-C)

时间:2017-05-19 02:48:43

标签: ios objective-c dispatch-async

我们假设我有以下代码

-(void)doSomething{
   [self expensiveMethod];
   [self otherMethod]; //Depends on above method to have finished
}

-(void)expensiveMethod{
 for(int i = 0; i<[someArray count]; i++{
     [self costlyOperation:someArray[i]];
  }
}

理想情况下,我希望[self costlyOperation]分离其他线程,以便每个线程都接近并行(当然我意识到这不可能)。在每个数组对象上完成[self costlyOperation]后,我希望它返回,以便[self otherMethod可以利用处理。

1 个答案:

答案 0 :(得分:1)

您可以使用默认队列使用dispatch async在后台运行任务。

修改

您可以为并行asyc执行分组异步任务。您可能需要根据您的要求稍微调整一下。

-(void)doSomething{
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        [self expensiveMethod:^{
            dispatch_async(dispatch_get_main_queue(), ^(void){
                //Run UI Updates
                [self otherMethod]; //Depends on above method to have finished
            });
        }];
    });
}

-(void)expensiveMethod:(void (^)(void))callbackBlock {

    dispatch_group_t group = dispatch_group_create();

    for(int i = 0; i<[someArray count]; i++) {
        __block int index = i;
        dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
            [self costlyOperation:someArray[index]];
        });
    }

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        if (callbackBlock) {
            callbackBlock();
        }
    });
}