我有一个 NSTimer 和一个 NSDate 一起工作来制作倒计时时钟。然后使用倒计时更新 UILabel。
我面临的问题是倒计时时钟在模拟器中有效,但在设备上无效。模拟器 iOS 6.0 和设备 iOS 6.0.1。
这是我的代码:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self startTimer];
}
// timer and update label to display a countdown clock
- (void)startTimer {
// Create a timer that fires every second repeatedly and save it in an ivar
NSTimer *timer = [[NSTimer alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}
- (void)updateLabel {
// convert date string to date then set to a label
NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
[dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"];
NSDate *date = [dateStringParser dateFromString:deadlineDate];
NSLog(@"date from update label %@", date);
NSTimeInterval timeInterval = [date timeIntervalSinceNow]; ///< Assuming this is in the future for now.
NSString *stringVariable = [self stringFromTimeInterval:timeInterval];
self.deadlineLbl.text = [NSString stringWithFormat:@"%@", stringVariable];
NSLog(@"%@",stringVariable);
}
- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
NSInteger ti = (NSInteger)interval;
// NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
return [NSString stringWithFormat:@"%02i hours : %02i min", hours, minutes];
}
这是首先在模拟器上然后在设备上的一些控制台输出:
模拟器控制台输出:
2012-11-14 15:39:57.021 appName[7856:13d03] 31 hours : 20 min
2012-11-14 15:39:58.020 appName[7856:13d03] 31 hours : 20 min
2012-11-14 15:39:59.021 appName[7856:13d03] 31 hours : 19 min
2012-11-14 15:40:00.021 appName[7856:13d03] 31 hours : 19 min
设备控制台输出:
2012-11-14 15:45:44.887 appName[7556:907] 00 hours : 00 min
2012-11-14 15:45:45.896 appName[7556:907] 00 hours : 00 min
2012-11-14 15:45:46.891 appName[7556:907] 00 hours : 00 min
2012-11-14 15:45:47.891 appName[7556:907] 00 hours : 00 min
我遇到的另一个问题是用户离开视图后计时器不断更新。
谢谢你的帮助