我希望在啓動應用程序時恢復時間計數器值。首先,我的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',核心數據,SQLite等)。然後,我們然後重新啓動應用程序,恢復開始時間,並將其用作顯示已過時間量的基礎。這是Swift,但這說明了一些關鍵問題:http://stackoverflow.com/questions/34496389/swift-nstimer-in-background/34497360#34497360 – Rob
然後當你想重新設置你的時間? – vaibhav
你想要設置定時器的值?以應用程序停止時的價值,還是考慮到應用程序會話之間的持續時間計算的值? – Cristik