Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through block while waiting for previous execution to finish

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?

like image 300
Andrew Avatar asked Jan 11 '23 23:01

Andrew


1 Answers

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

    }
like image 189
Chamira Fernando Avatar answered Jan 31 '23 07:01

Chamira Fernando