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
私が抱えている別の問題は、ユーザーがビューを離れた後もタイマーが更新され続けることです。
助けてくれてありがとう