我有一个代码块,它循环遍历一个数组并在其上执行块代码。目前它看起来像这样:
for (NSString *myString in myArray) {
[self doSomethingToString:myString WithCompletion:^(BOOL completion) {
string = [NSString stringByAppendingString:@"Test"];
}];
}
我想在开始下一次迭代之前等待上一次迭代完成。我怎样才能像这样循环一些块代码呢?
答案 0 :(得分:8)
试试这个
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
for (NSString *myString in myArray) {
[self doSomethingToString:myString WithCompletion:^(BOOL completion) {
string = [NSString stringByAppendingString:@"Test"];
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
答案 1 :(得分:0)
你可以使用
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
string = [NSString stringByAppendingString:@"Test"];
}];
答案 2 :(得分:0)
Swift 3.1
var sema = DispatchSemaphore(value: 0)
for myString: String in myArray {
doSomething(to: myString, withCompletion: {(_ completion: Bool) -> Void in
string = String + ("Test")
dispatch_semaphore_signal(sema)
})
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
dispatch_release(sema)
}