how to display seconds using nstimer?
I am working on a game project. I need to know that how can I display the seconds when game is started to the end of game ? also need to display in format of " 00:01 " . additional if time goes to b开发者_如何学Goeyond the 60 min than it should also display the hours " 1:00:01 "
any guidance ?
Thanks...
After combining the answers of Nathan and Mark the complete timer method could look something like this:
- (void)timer:(NSTimer *)timer {
NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
NSInteger seconds = secondsSinceStart % 60;
NSInteger minutes = (secondsSinceStart / 60) % 60;
NSInteger hours = secondsSinceStart / (60 * 60);
NSString *result = nil;
if (hours > 0) {
result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
else {
result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
// set result as label.text
}
when you start the game you set the startDate and start the timer like this:
self.startDate = [NSDate date];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
when stopping the game you use this:
self.startDate = nil;
[timer invalidate];
timer = nil;
You can schedule a repeating timer that fires every second, when it fires it calls a method that updates your time display:
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
Then in the update method
- (void)timerFireMethod:(NSTimer*)theTimer {
//remove a second from the display
}
You'll want to set the timer to an attribute so that it can be invalidated when finished.
NSTimeInterval t = 10000; printf( "%02d:%02d:%02d\n", (int)t/(60*60), ((int)t/60)%60, ((int)t)%60 );
outputs 02:46:40
if you want to get the seconds with decimal points then it is a little more difficult you have to use mode().
精彩评论