Reputation: 7883
I have a block of code which loops through an array and performs block code on it. Currently it looks like this:
for (NSString *myString in myArray) {
[self doSomethingToString:myString WithCompletion:^(BOOL completion) {
string = [NSString stringByAppendingString:@"Test"];
}];
}
I want to wait for the previous iteration to finish before I start on the next one. How can I loop through some block code like this?
Upvotes: 5
Views: 2364
Reputation: 13
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)
}
Upvotes: 0
Reputation: 6846
Try this
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);
}
Upvotes: 9
Reputation: 12023
you can use
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
string = [NSString stringByAppendingString:@"Test"];
}];
Upvotes: 0