tags:

views:

45

answers:

2

As in most games i hv seen the timer in a format "01:05"

I m trying to implement a timer, and on reset i need to reset the timer to "00:00".

This timer value should be in label.

How to create a timer which is incrementing? like 00:00---00:01---00:02..........somthing like dat.

suggestions

regards

+1  A: 

A Simple way I've used is this:

//In Header
int timeSec = 0;
int timeMin = 0;
NSTimer *timer;

//Call This to Start timer, will tick every second
-(void) StartTimer
{
     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode];
}

//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer *)timer
{
     timeSec++;
     if (timeSec == 60)
     {
        timeSec = 0;
        timeMin++;
     }
     //Format the string 00:00
     NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
     //Display on your label
     [timeLabel setStringValue:timeNow];
}

//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer
{
    [timer invalidate];
    timeSec = 0; 
    timeMin = 0;
     //Since we reset here, and timerTick won't update your label again, we need to refresh it again.
     //Format the string in 00:00
     NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
     //Display on your label
     [timeLabel setStringValue:timeNow];
}
Hector204
thanks Hector for replying. i am getting error at "NSEventTrackingRunLoopMode" ...how to define this???
shishir.bobby
Try changing it to: [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
Hector204
ok will try......
shishir.bobby
done...thanks man..upvoted
shishir.bobby
@hector, can we pause timer???
shishir.bobby
+1  A: 

Hi,

create an object of NSDate type e.g.'now'. After that follow the code below:

self.now = [NSDate DAte];
long diff = -((long)[self.now timeIntervalSinceNow]);
timrLabel.text = [NSString stringWithFormat:@"%02d:%02d",(diff/60)%60,diff%60];
anurag85