【发布时间】:2024-01-11 06:44:02
【问题描述】:
我有一个基本上是时钟、秒表和计时器的 iPhone 应用程序。一切正常,直到您离开应用程序,秒表和计时器停止计数。我认为解决这个问题的方法是在应用程序进入后台时启动一个计数器,并在应用程序再次启动时从秒表/计时器中添加/减去它。这是最好的做法吗?如果是,我该怎么做?
更新:计时器、秒表和时钟都在不同的视图控制器中。这是我的秒表在 StopwatchViewController.m 中的代码:
- (void)stopwatch // Start counting the stopwatch
{
hourInt = [hourLabel.text intValue]; // Store integer values of time
minuteInt = [minuteLabel.text intValue];
secondInt = [secondLabel.text intValue];
if (secondInt == 59) { // Add on one second
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt]; // Update text to show time
NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:NO]; // Repeat every second
}
如何让它添加应用程序在后台运行的时间?
【问题讨论】:
标签: ios objective-c timer