【发布时间】:2017-05-14 15:45:20
【问题描述】:
我想在启动应用程序时恢复时间计数器值。首先我的 label 值是 05:00,而不是关闭应用程序后,但是当我再次启动应用程序时,时间计时器计数开始到 05:00。请帮帮我
int timeSec,timeMin ;
- (void)viewDidLoad {
timeSec=0;
timeMin=0;
[self StartTimer];
}
-(void) StartTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer *)timer
{
timeSec++;
if (timeSec == 60)
{
timeSec = 0;
timeMin++;
}
//Format the string 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
//[timeLabel setStringValue:timeNow];
self.lbl_timer.text= timeNow;
}
//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer
{
// [timer invalidate];
timeSec = 0;
timeMin = 0;
//Since we reset here, and timerTick won't update your label again, we need to refresh it again.
//Format the string in 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
// [timeLabel setStringValue:timeNow];
self.lbl_timer.text= timeNow;
}
感谢您的提前..
【问题讨论】:
-
将计时器开始时间保存在持久存储中的某处(例如
NSUserDefaults、Core Data、SQLite 等)。然后,我们重新启动应用程序,恢复该开始时间,并将其用作显示已用时间量的基础。它是 Swift,但这说明了一些关键问题:stackoverflow.com/questions/34496389/… -
然后当你想重新设置你的时间?
-
您想将计时器设置为哪个值?是应用停止时的值,还是考虑到应用会话之间的持续时间计算得出的值?
标签: ios objective-c nstimer