每次页面加载时,计时器的减量会有所不同 [英] Timer decrement gets varied for each page load
问题描述
我的项目有一个计时器,每次减少1秒.但是,如果计数器第二次开始工作,则递减2秒,第三次减少3秒,以此类推.我应该怎么做才能始终使1秒递减?
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];
}
推荐答案
根据您发布的内容,您正在创建多个计时器,而不是停止其中的任何一个.因此,经过3次之后,您每秒就有3个计时器触发.
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]
但是您可能还需要考虑保留您创建的计时器(以@property表示),以便如果用户在计数器实际为零之前以其他方式离开此视图,则可以使计时器无效并释放它.
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.
希望有帮助.
这篇关于每次页面加载时,计时器的减量会有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!