Search code examples
objective-cfor-loopcocos2d-iphonedelaygrand-central-dispatch

Objective C for loop delay


I have a for loop that I want to add a delay between iterations. I have changed waitUntilDone to YES and get the same results. My array only has two numbers in it and both are called after the five seconds instead of:

0s - nothing 5s - Block called 10s- Block called

for(NSNumber* transaction in gainsArray) {

    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

        NSLog(@"Block");

        [self performSelectorOnMainThread:@selector(private_addTransactionToBankroll:)
        withObject:transaction waitUntilDone:NO];

    });
}

2015-06-16 20:11:06.485 TestApp[97027:6251126] Block
2015-06-16 20:11:06.485 TestApp[97027:6251127] Block

I am using Cocos2d if that matters


Solution

  • The for loop will dispatch one right after the other so they will essentially delay for the same time.
    Instead set a different increasing delay for each:

    double delayInSeconds = 0.0;
    for(NSNumber* transaction in gainsArray)
    {
        delayInSeconds += 5.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
                       {
                           NSLog(@"Block");
                           [self performSelectorOnMainThread:@selector(private_addTransactionToBankroll:)
                                                  withObject:transaction
                                               waitUntilDone:NO];
    
                    });
    }