0

I was just wondering, if there was any way of pausing a for loop.

For instance,

for (i = 0; i<10 ; i++) {

NSLog(i);
//Pause should go here
}

The outcome should be: 1 (wait 1 sec) 2 (wait 1 sec) etc.

Firstly, I thought that you could add SKAction *wait = [SKAction waitForDuration:1 completion:^{ , but then I wasn't sure if you could resume the loop from inside the completion brackets.

I have looked around and found NSTimer, but I am not sure how you could implement this, because I would have to call the loop after each interval and it i would never be more than 0.

Is there any way that you could pause the loop for an amount of time, then have it resume enumerating?

1 Answers1

2

As a matter of style you'd normally reformat the loop to be tail recursive. So, instead of:

for(i = 0; i < 10; i++) {
    // ... work here ...
}

You'd reformulate as:

void doWorkForIteration(int i, int limit) {
    if(i == limit) return;

    // ... work here ...

    doWorkForIteration(i+1, limit);
}

... 
doWorkForIteration(0, 10);

It recurses because it call itself. It is tail recursive because its recursive call is the very last thing it does.

Once you've done that, you can switch from a direct recursive call to a delayed one. E.g. with GCD:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^{
    doWorkForIteration(i+1, limit);
});

... or use [self performSelector: withObject: afterDelay:] or any of the other deferred call approaches.

To do literally what you want, you could use C's sleep call. But that thread will block for the number of seconds specified. So don't do it on the main thread unless you want your application to lock up.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • 3
    Note that using GCD, NSTimer, performSelector are not recommended for use with Sprite Kit. It's best to implement such behavior using SKAction, as this is the only way to ensure that such tasks are properly paused and resumed when the app is paused or enters background. – CodeSmile Jan 09 '15 at 16:32
  • 3
    Using a combination of `SKAction`s is a better option. – 0x141E Jan 09 '15 at 17:20
  • 1
    @LearnCocos2D I must admit to present ignorance about `SKAction`; I've marked the answer as community wiki — I don't suppose you could correct? – Tommy Jan 09 '15 at 17:20
  • @0x141E the same invite goes to you; we just had an unfortunate synchronicity of posting. – Tommy Jan 09 '15 at 17:29