首页 > 解决方案 > 暂停游戏后如何从停止的地方重新启动游戏计时器?

问题描述

我在 Xcode 9.3 和 Objective-C 中做文字游戏。

我的手机上安装了 iOS 11.3.1 的游戏,如果我在游戏中接到电话,它会被电话取代。然后在通话后游戏重新出现并从中断的地方恢复。所有这些都无需添加任何代码。

当游戏被用户打断时,我正在尝试做同样的事情,例如按下主页按钮。

所以我有;

- (void)applicationWillResignActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopTimer" object:self];
}

和:

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"startTimer" object:self];
}

而且因为

@interface ViewController ()
@property (strong, nonatomic) WRWGameController* controller;
@end

在游戏控制器中我有

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopTimer)        
                                            name:@"stopTimer"
                                          object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startTimer)
                                             name:@"startTimer"
                                           object:nil];

计时器在非活动状态下停止,但当游戏重新开始时,计时器在 00.00 重新开始。

我在这里查看了各种停止和启动计时器的帖子,但还没有找到将代码合并到我的应用程序中的方法,因此计时器在它停止的地方再次启动。

标签: iosobjective-ctimer

解决方案


您需要将开始时间保存到 NSDate 实例变量:

@property (strong, nonatomic) NSDate *startTime;

然后在 startTimer 方法中保存日期:

self.startTime = [NSDate date];

然后,当您停止计时器时,您可以使用

NSTimeInterval elapsedTime = -[self.startTime timeIntervalSinceNow];

当您重新开始时间时,只需从您在计时器中使用的时间间隔中减去 elapsedTime。


推荐阅读