在viewcontroller中使用nstimer
我有一个场景,我需要在按钮点击启动/停止计时器。我可能会从页面移动并再次返回,但计时器应该正在运行。为此,我在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.
谢谢
潘卡
没有找到相关结果
已邀请:
1 个回复
素汞读
移除线
释放自己并再次尝试。我注意到的另一件事是:定时器应该始终由MainThread创建,否则它将不会开始执行。 //编辑:尝试此代码再次启动它: