I have a timer for my project, each time it decrements by 1 second. But if the counter starts working for the second time it gets decremented by 2 seconds and for the third time by 3 seconds etc. what should I do to get 1 sec decrement for all the time?
-(void)viewDidAppear:(BOOL)animated {
count=15; //timer set as 15 seconds
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:)userInfo:nil repeats:YES]; //for decrementing timer
}
- (void)updateCounter:(NSTimer *)theTimer {
count -= 1;
NSString *s = [[NSString alloc] initWithFormat:@"%d", count];
if(count==0) // alert for time expiry
{
alert = [[UIAlertView alloc] initWithTitle:@"Time Out!!" message:@"Your time is expired." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
self.timer.hidden=YES;
[self dismissModalViewControllerAnimated:YES];
}
else {
self.timer.text = s;
}
[s release];
}
From what you’ve posted, you’re creating multiple timers and not stopping any of them. So after 3 times, you have 3 timers firing each second.
At a minimum, when the timer hits zero you want to invalidate it:
[theTimer invalidate]But you may also want to consider holding onto the timer you create (in a @property) so that you can invalidate and release it if the user leaves this view some other way before your counter actually goes to zero.
Hope that helps.