只有在方法完成后才继续循环 [英] only continue loop if method has finished
问题描述
我有一个 for / in
循环如下:
for(NSString *paymentId in success){
[self getPaymentDetails:paymentId];
}
方法 getPaymentDetails
是异步的。如果方法已完成,如何创建完成块以仅继续for / in循环?
The method getPaymentDetails
is asynchronous. How do I create a completion block to only continue the for/in loop if the method has finished?
- 详细信息
方法 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
The definition of "finished" is hereby defined when the amount as well as the currency has been stored in the array. Or in other words: when the code block has reached the end of the method for that specific paymentId
推荐答案
您可以使用信号量进行这种同步。信号量是并发的基本构建块,并且提供非忙等待。 GCD通过 dispatch_semaphore-create
, dispatch_semaphore_signal
和 dispatch_semaphore_wait
。
You can use semaphores for this kind of synchronisation. Semaphores are a basic building block in concurrency and provide among other things non-busy waiting. GCD provides semaphores through dispatch_semaphore-create
, dispatch_semaphore_signal
and dispatch_semaphore_wait
.
在非常一般的大纲中,首先创建一个信号量:
In very general outline first create a semaphore:
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
然后在循环中等待此信号量:
then in your loop wait on this semaphore:
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
command),为信号量找到一本书(或互联网)。
For more details on the API see the manual (man
command), for semaphores find a book (or the internet).
HTH
这篇关于只有在方法完成后才继续循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!