我有一个应用程序,它使用从 0 开始的秒表式计数,采用 HH:mm:ss 格式。代码对我来说看起来很简单,我想不出更有效的方法来运行它。
出于某种原因,当我运行它时,当计时器到达 00:00:02 时,会有一个非常明显且一致的(每次我运行它,在同一个地方)滞后。它在 00:00:02 停留整整一秒钟,然后正常计数。为什么会发生这种情况?
-(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;
}