ios - 暂停游戏后如何从停止的地方重新启动游戏计时器?
问题描述
我在 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];
当您重新开始时间时,只需从您在计时器中使用的时间间隔中减去 elapsedTime。
推荐阅读
- php - PHP:将日期格式 d/m/Y h:i:sa 更改为 m/d/Y h:i:sa
- javascript - 有没有基于多组组合生成数据集的JS函数
- python - 如何检查以确保字符串中没有字母?
- android - React Native - navigation.addListner 不是对象
- java - 如何在 xml 的对话框中添加按钮?
- c# - 从 div 内的某些元素中选择文本并忽略其他元素。HTML 敏捷包
- mysql - 当值不存在时返回 MySQL 中的默认行
- javascript - 为什么我在导入 React 时会出错
- oracle - 未创建 Oracle 集成实例
- javascript - Angular observable 使用订阅检索数据