Reputation:
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?
Upvotes: 0
Views: 343
Reputation: 100622
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.
Upvotes: 2