我正在用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 再次启动。
我在这里查看了各种停止和启动计时器帖子,但还没有找到将代码合并到我的应用程序中的方法,以便计时器从中断的地方再次启动。
您需要将开始时间保存到 NSDate 实例变量:
@property (strong, nonatomic) NSDate *startTime;
然后在 startTimer 方法中保存日期:
self.startTime = [NSDate date];
然后,当您停止计时器时,您可以使用以下命令获取经过的时间
NSTimeInterval elapsedTime = -[self.startTime timeIntervalSinceNow];
当您重新开始时间时,只需从计时器中使用的间隔中扣除已用时间。