Wait for an async methods to finish in a for loop

前端 未结 4 829
庸人自扰
庸人自扰 2021-02-09 14:38

I have a for loop containing three asynchronous methods, and I want to make some treatment after this 3 async methods are finished.

 -(void)getAllUsersInformatio         


        
4条回答
  •  无人及你
    2021-02-09 15:25

    Try to do a block with completion, you can't do this with a for loop if the methods are async. you have to call getUserInfo one by one after the completion of the previous. I think this gonna be solved your problem.

      -(void)getAllUsersInformations{
        [self registerUserAtIndex:0];
      }
    
      - (void) registerUserAtIndex: (NSInteger ) userIndex
      {
      RegisterOperation *op = [[RegisterOperation alloc] initWithUser:[users objectAtIndex:userIndex]];
      [RegisterOperation setResultCompletionBlock:^(BOOL *finished, NSInteger userIndex) {
          dispatch_async(dispatch_get_main_queue(), ^{
          if (userIndex++ < [users count] {
             [self registerUserAtIndex:userIndex++];
          } else {
             [myTableView reloadData];
          }
       }];
      [[NSOperationQueue mainQueue] addOperation:op];
     }
    

    Hope this will help you.

提交回复
热议问题