我有一个倒数计时器,从当前日期开始直到10分钟。
当我在视线上时,它完全正常倒计时,但是当我改变视图并返回时,计时器停止,是否有人能指出我正确的方向?
-(void)updateCountdown {
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponants = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger minutes = [dateComponants minute];
NSInteger seconds = [dateComponants second];
NSString *countdownText = [NSString stringWithFormat:@"Free Check: %ld:%ld", (long)minutes, (long)seconds];
timeLabel.text = countdownText;
NSLog (@"Startdate is %@", startingDate);
NSLog(@"Enddate is %@", endingDate);
//Attempt at saving the time but I guess this only saves the text?
NSString * saveStringTime = timeLabel.text;
NSUserDefaults * defaultsTime = [NSUserDefaults standardUserDefaults];
[defaultsTime setObject:saveStringTime forKey:@"saveStringTime"];
[defaultsTime synchronize];
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
我想我的ViewDidLoad中需要一些东西来获取它的时间并把它放回去?
谢谢
答案 0 :(得分:1)
你必须在viewWillAppear中获取“savedStringTime”才能从“savedTime”恢复。由于viewDidLoad仅在视图加载到内存时才会被调用,因此当用户导航回同一视图时,将不会调用viewDidLoad(因为视图仍在内存中)。
为了正常工作,调用你的方法在“viewWillDisappear”和“viewWillAppear”中保存时间,检查“savedStringTime”是否可用,如果是,则恢复它或者启动一个新的计数器。