我有一个场景,我需要在点击按钮时启动/停止计时器。我可能会离开页面并再次返回,但计时器应该正在运行。为此,我在viewWillDisappear方法中停止并释放它,然后根据viewWillAppear中的一个条件重新启动它。但它不会再开始了。以下是我的代码:
- (void)viewWillDisappear:(BOOL)animated {
if([timerInterval isValid]) {
[timerInterval invalidate];
//[timerInterval release];
timerInterval = nil;
}}
- (void)viewWillAppear:(BOOL)animated {
HealthyBabyAppDelegate *appDel = (HealthyBabyAppDelegate *)[[UIApplication sharedApplication] delegate];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[appDel changeBackground]]];
if(appDel.contractionDutation>0) {
//if(timerInterval==nil)
timerInterval = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(printInterval) userInfo:nil repeats:YES];
}}
-(IBAction)Contraction:(id)sender {
HealthyBabyAppDelegate *appDel = (HealthyBabyAppDelegate *)[[UIApplication sharedApplication] delegate];
if([(UIButton*)sender tag]==2) {//stop the contrction
[(UIButton*)sender setTag:1];
[(UIButton*)sender setTitle:@"Start" forState:UIControlStateNormal];
[appDel startContractionTimer:FALSE];
[timerInterval invalidate];
//timerInterval = nil;
}
else {//start the contraction, 2 means contraction is running
[(UIButton*)sender setTag:2];
[(UIButton*)sender setTitle:@"Stop" forState:UIControlStateNormal];
[appDel startContractionTimer:TRUE];
([[tblContractionDetail cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] textLabel]).text = [NSString stringWithFormat:@"Start Time: %@",appDel.contractionStartTime];
timerInterval = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(printInterval) userInfo:nil repeats:YES];
}}
Contraction method will stop/delete the timer. 感谢Pankaj
发布于 2010-12-22 16:38:30
不应该发布NSTimer。它将通过触发invalidate来释放自身,删除行timerInterval = nil;,然后重试。我自己注意到的另一件事是:计时器应该总是由MainThread创建的,否则它不会开始执行。
//EDIT:尝试此代码以再次启动:
// inside your function
[self performSelectorOnMainThread:@selector(startUpdate) withObject:nil waitUntilDone:YES];
-(void)startUpdate {
updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(doSomething)
userInfo:nil
repeats:YES];
}https://stackoverflow.com/questions/4507111
复制相似问题