Search code examples
iosobjective-cnsstringnsarrayblock

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?


Solution

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