2010-10-21 23 views
0

我想使用timeIntervalSinceReferenceDate,我不太确定如果我理解正确。我基本上有一个按钮来计算按下开始和停止按钮之间的时间差异。在iPhone中的简单定时器

- (IBAction)startButtonPressed { 
    startButtonFlag = !startButtonFlag; // first time through, startButtonFlag turns on 
    if (startButtonFlag) { // timer starts 
     [startButton setTitle:@"Stop" forState:UIControlStateNormal]; 
     startTime = [NSDate timeIntervalSinceReferenceDate]; 
     NSLog(@"start time: %d", startTime); 
    } 
    else { // timer stops 
     [startButton setTitle:@"Start" forState:UIControlStateNormal]; 
     stopTime = [NSDate timeIntervalSinceReferenceDate]; 
     NSLog(@"stop time: %d", stopTime);  
     elapsedTime = stopTime - startTime; 
     NSLog(@"elapsed time: %d", elapsedTime); 
    } 

} 

我不太了解输出。我的样本输出是: 开始时间:558828278 停止时间:581239552 经过时间:-1610612736

我按下后不久停止按钮(5秒左右)之后我按下开始。我期待停止时间更像558828283,所以当我减去两次时,看看已经过了多少时间,我会得到5秒。我误解了类方法的工作原理吗?谢谢。

回答

1

正在开始时间,停止时间,并elapsedTime声明为类型NSTimeInterval或双?

在这种情况下,您应该使用%f而不是%d(用于整数)。

+0

谢谢。出于某种原因,我认为%d是十进制的。 – Crystal 2010-10-21 03:13:06

+0

请参阅[字符串格式说明符](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Strings/Articles/formatSpecifiers.html%23//apple_ref/doc/uid/TP40004265)。 – Anna 2010-10-21 03:16:04

1

你可以尝试这样的事情,而不是:

NSDate* start = [NSDate date]; 
... 

NSDate* stop = [NSDate date]; 
NSLog(@"took %lf seconds", [stop timeIntervalSinceDate:start]); 
0

你使用了错误的功能:

[NSDate timeIntervalSinceReferenceDate]; 

创建并返回从1 2001年1月,GMT第一个即时设置为秒给定数量的一个NSDate对象。

你应该使用类似

dateWithTimeIntervalSinceNow 

创建并返回设置为从当前日期和时间给定的秒数一个NSDate对象。