最佳实践 - 在ObjC中顺序执行命令

时间:2014-02-27 17:42:11

标签: ios objective-c

按特定顺序执行一系列命令的最佳方法是什么?我一直对ObjC中执行的并发性感到沮丧。这是其中一种情况,我意识到我是一名设计师,而不是一名“真正的”编码员。

我正在iOS上试验SpriteKit,当能量计达到<= 0时,我想要发生一系列事情。

  1. 调用方法在最终联系人处创建爆炸。该方法对爆炸的位置和大小进行了论证。
  2. 之后调用另一个调用新场景,结果屏幕的方法。
  3. 我的问题发生在新场景被调用之前我有机会看到最后一次爆炸。

    以下是相关代码:

    - (void) doGameOver
    {
        damageIndicator.progress = 0;
        energyLeft.text = @"Energy:0%";
        GameOver *newScene = [[GameOver alloc]initWithSize:self.size];
        newScene.timeElapsed = [started timeIntervalSinceNow];
        [self.view presentScene:newScene transition:[SKTransition fadeWithColor:[SKColor whiteColor] duration:1]];
    [damageIndicator removeFromSuperview];
    

    }

    - (void) makeExplosionWithSize:(float)myBoomSize inPosition:(CGPoint)boomPosition
    {
    NSString *myFile = [[NSBundle mainBundle] pathForResource:@"explosion" ofType:@"sks"];
    SKEmitterNode *boom = [NSKeyedUnarchiver unarchiveObjectWithFile:myFile];
    boom.position = boomPosition;
    boom.particleSize = CGSizeMake(myBoomSize, myBoomSize);
    [self addChild:boom];
    [self runAction:self.playMySound];
    

    }

    - (void)adjustScoreWithDamage:(float)hitDamage atPosition:(CGPoint)pos
    {
    _damage = _damage -(hitDamage);
    if (_damage < 0) {
    //these are the two things I need to execute sequentially
        [self makeExplosionWithSize:500 inPosition:pos];
        [self doGameOver]
    }
    

    }

    我尝试过使用bools的方案(gameOver = YES),但我想我可能需要创建一个完成处理程序,这只会让我头晕目眩。

    有人能建议用最简单的方式来完成此任务吗?

    提前谢谢。

2 个答案:

答案 0 :(得分:1)

我可能会误解你的目标,但听起来应该是:

  1. 爆炸开始了。
  2. 暂停[n]秒。
  3. 显示游戏结束屏幕。
  4. 要实现这一点,您可能只想使用NSTimer触发“doGameOver”,而不必担心在爆炸完成后立即触发它。

    以下是延迟3秒的示例:

    NSTimer *gameOverTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(doGameOver:) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:gameOverTimer forMode:NSDefaultRunLoopMode];
    

答案 1 :(得分:1)

最简单(不是最好的)可能是替换

[self doGameOver];

[self performSelector:@selector(doGameOver) withObject:nil afterDelay:2.0];
相关问题