Waiting for multiple blocks to finish

后端 未结 5 642
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 09:33

I have those methods to retrieve some object information from the internet:

- (void)downloadAppInfo:(void(^)())success
                failure:(void(^)(NSErr         


        
5条回答
  •  死守一世寂寞
    2020-12-28 09:55

    You were almost there, the problem is most likely to be that those methods are asynchronous, so you need an extra synchronization step. Just try with the following fix:

    for(Appliance *appliance in _mutAppliances) {
      dispatch_group_async(
         group,
         dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           dispatch_semaphore_t sem = dispatch_semaphore_create( 0 );
    
           NSLog(@"Block START");
    
           [appliance downloadAppInfo:^{
              NSLog(@"Block SUCCESS");
                dispatch_semaphore_signal(sem);
           }
           failure:^(NSError *error){
             NSLog(@"Block FAILURE");
             dispatch_semaphore_signal(sem);
           }];
    
           dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    
           NSLog(@"Block END");
     });
    
     dispatch_group_notify(
       group,
       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
         NSLog(@"FINAL block");
         success();
     });
    }
    

提交回复
热议问题