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

混江龙づ霸主 提交于 2019-12-12 18:17:57

问题


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");

回答1:


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.



来源:https://stackoverflow.com/questions/22285374/ios7-spritekit-how-to-wait-for-an-animation-to-complete-before-resuming-method-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!