【发布时间】:2026-01-15 21:50:02
【问题描述】:
我已经研究了如何在按下主页按钮时保持计时器运行。但我很困惑。
这是我的代码,我该如何修复它并且计时器继续在后台运行?提前致谢。
-(id)init {
if (self = [super init]) {
self.timer = [[NSTimer alloc] init];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
}
return self;
}
+(Timer *)sharedSingleton {
static Timer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [[Timer alloc] init];
});
return sharedSingleton;
}
-(void)startTimer {
i++;
_count = [NSNumber numberWithInteger:i];
[[NSNotificationCenter defaultCenter] postNotificationName:COUNT object:_count];
}
【问题讨论】:
-
如果应用程序在后台,您是否希望在计时器结束时发生任何事情?或者如果应用程序再次被带到前面,您是否希望计时器像以前一样继续(减去它在后台的任何时间)?
-
我希望计时器在应用程序处于后台时继续计时。提前致谢。
-
为什么需要定时器在后台运行?您的应用将无法运行。
-
当您的应用程序进入后台时,节省时间。当它在前台恢复时,获取当前时间。从当前时间中减去保存的后台时间,您就会知道您的计时器已经运行了多长时间。
-
不是“可能一个好主意”。这是正确的解决方案。您的应用程序可能会在后台被杀死。当用户尝试返回应用程序时,您需要处理该应用程序被杀死并重新启动。
标签: ios objective-c