Scroll block waiting for previous execution to complete

I have a block of code that goes through an array and executes 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 until the end of the previous iteration before I start the next. How can I skip some block code?

+4
source share
3 answers

try it

    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);

    }
+7
source

you can use

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
   string = [NSString stringByAppendingString:@"Test"];
}];
0
source

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)
}
0
source

All Articles