如果方法已完成,则仅继续循环

时间:2014-08-31 23:09:35

标签: ios objective-c multithreading concurrency

我有一个for/in循环:

for(NSString *paymentId in success){
   [self getPaymentDetails:paymentId];
}

方法getPaymentDetails是异步的。如果方法已完成,如何创建完成块以仅继续for / in循环?

  • 细节

方法getPaymentDetails如下所示:

-(void)getPaymentDetails:(NSString *)paymentId{

  PFUser *currentUser = [PFUser currentUser];
  [PFCloud callFunctionInBackground:@"getpaymentdetails"
                     withParameters:@{@"objectid": paymentId, @"userid": currentUser.objectId}
                              block:^(NSDictionary *success, NSError *error) {
                                if(success){
                                  NSDictionary *payment = success;
                                  NSString *amount = [payment objectForKey:@"amount"];
                                  if (![amount isKindOfClass:[NSNull class]]) {
                                    [self.amountArray addObject:amount];
                                  }
                                  else {
                                    [self.amountArray addObject:@""];
                                  }

                                  NSString *currency = [payment objectForKey:@"currency"];
                                  if (![currency isKindOfClass:[NSNull class]]) {
                                    [self.currencyArray addObject:currency];
                                  }
                                  else {
                                    [self.currencyArray addObject:@""];
                                  }

                                  [self.tableView reloadData];

                                } else{

                                  NSLog(@"Error logged getpaymentdetails: %@", error);
                                }
                          }];

}

当数量和货币已存储在数组中时,定义“已完成”的定义。或者换句话说:当代码块到达特定paymentId

的方法的末尾时

1 个答案:

答案 0 :(得分:1)

您可以使用信号量进行此类同步。信号量是并发中的基本构建块,并提供非忙等待等。 GCD通过dispatch_semaphore-createdispatch_semaphore_signaldispatch_semaphore_wait提供信号量。

总的来说,首先要创建一个信号量:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

然后在你的循环中等待这个信号量:

for(NSString *paymentId in success)
{
   [self getPaymentDetails:paymentId];
   dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); // wait for call to signal completion
}

然后在背景块信号完成的适当位置:

dispatch_semaphore_signal(sema);

有关API的更多详细信息,请参阅手册(man命令),以便信号量找到一本书(或互联网)。

HTH