Simple timer in iPhone
I'm trying to use timeIntervalSinceReferenceDate and I'm not quite sure if I understand it correctly. I basically have a button to calculate the difference in time between when the start and stop button is pressed.
- (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);
}
}
I don't quite understand the output. My sample output is: start time: 558828278 stop time: 581239552 elapsed tim开发者_运维知识库e: -1610612736
I pressed the stop button shortly after (5 seconds or so) after I pressed start. I was expecting that the stop time would be more like 558828283 so when I subtracted the two times, to see how much time has elapsed, I would get 5 seconds. Am I misunderstanding how the class method works? Thanks.
Are startTime, stopTime, and elapsedTime declared as type NSTimeInterval or double?
In that case, you should use %f
instead of %d
(which is for ints).
you could try something like this instead:
NSDate* start = [NSDate date];
...
NSDate* stop = [NSDate date];
NSLog(@"took %lf seconds", [stop timeIntervalSinceDate:start]);
Your using the wrong function:
[NSDate timeIntervalSinceReferenceDate];
Creates and returns an NSDate object set to a given number of seconds from the first instant of 1 January 2001, GMT.
You should be using something like
dateWithTimeIntervalSinceNow
Creates and returns an NSDate object set to a given number of seconds from the current date and time.
精彩评论