Alex Stone
Alex Stone

Reputation: 47348

iOS7 SpriteKit how to wait for an animation to complete before resuming method execution?

Is there a way to make a method wait for a SpriteKit action initiated within the method to complete before continuing code execution? Here's what I have so far, but it just hangs at the wait loop.

    __block BOOL  wait = YES;

    SKAction* move = [SKAction moveTo:destination duration:realMoveDuration];
    SKAction* sequence  = [SKAction sequence:@[[SKAction waitForDuration:0.07],move,[SKAction waitForDuration:0.07] ]];

    [spellEffect runAction:sequence  completion:^{
        [spellEffect removeFromParent];
        wait = NO;
    }];
    DLog(@"Waiting");
    while (wait) {

    }

    DLog(@"Done waiting");

Upvotes: 2

Views: 2979

Answers (1)

Logan
Logan

Reputation: 53112

I think you have a misunderstanding about the execution of blocks, apple has great docs: here. Your while loop will run infinitely, and even if the block did stop it, using that type of system to block your main thread will likely get your app shot down during review.

You should continue within the block. If for instance, you wanted to continue with a method called continueAfterAnimationIsDone, you could do

// Runs first
[spellEffect runAction:sequence  completion:^{
    [spellEffect removeFromParent];
    wait = NO;
    // Done
    // Runs third
    [self continueAfterAnimationIsDone]; // this method won't start until animations are complete.
}];
// Runs second

Note that when you are declaring the block, the code within it is captured and animations begin on a background thread. The rest of your code continues, so you're waiting loop will start. Once animations are completed this block executes, but it doesn't have a way to properly notify your while loop and so the loop never ends. Let me know if you have further questions, blocks can be strange.

Upvotes: 6

Related Questions