我的项目有一个计时器,每次减少 1 秒。但是,如果计数器第二次开始工作,它会减少 2 秒,第三次则减少 3 秒,依此类推。我应该怎么做才能始终减少 1 秒?
-(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 个计时器。
至少,当计时器达到零时,您希望使其无效:
[theTimer invalidate]
但是您可能还需要考虑保留您创建的计时器(在 @property 中),以便在您的计数器实际变为零之前用户以其他方式离开此视图时,您可以使其无效并释放它。
希望有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)