HH:mm:ss 形式で 0 からカウントアップするストップウォッチ スタイルのアプリを使用しています。コードは私には非常に単純に見えますが、これ以上効率的に実行する方法は思い浮かびません。
何らかの理由で、タイマーを実行すると、タイマーが 00:00:02 になると、非常に顕著で一貫した (同じ場所で実行するたびに) 遅延が発生します。00:00:02 に 1 秒間とどまり、その後は通常どおりカウントされます。なぜこれが起こるのでしょうか?
-(IBAction)startAndStop;
{
if (!timer) {
NSLog(@"Pressing Start Button");
[startAndStopButton setTitle:@"Stop" forState:0];
startDate = [[NSDate date] retain];
timerLabel.text = @"00:00:00";
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timerStart)
userInfo:nil
repeats:YES];
} else {
NSLog(@"Pressing Stop Button");
[startAndStopButton setTitle:@"Start" forState:0];
[startDate release];
[timer invalidate];
timer = nil;
[timer release];
}
}
-(void)timerStart
{
NSDate *currentDate = [NSDate date];
NSTimeInterval countInSeconds = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSinceReferenceDate:countInSeconds];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss"];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [df stringFromDate:timerDate];
[df release];
timerLabel.text = timeString;
}