首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在视图控制器中使用nstimer

在视图控制器中使用nstimer
EN

Stack Overflow用户
提问于 2010-12-22 15:38:17
回答 1查看 534关注 0票数 0

我有一个场景,我需要在点击按钮时启动/停止计时器。我可能会离开页面并再次返回,但计时器应该正在运行。为此,我在viewWillDisappear方法中停止并释放它,然后根据viewWillAppear中的一个条件重新启动它。但它不会再开始了。以下是我的代码:

代码语言:javascript
运行
复制
- (void)viewWillDisappear:(BOOL)animated {
if([timerInterval isValid]) {
    [timerInterval invalidate];
    //[timerInterval release];
    timerInterval = nil;
}

}

代码语言:javascript
运行
复制
- (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];
}

}

代码语言:javascript
运行
复制
-(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];
}

}

代码语言:javascript
运行
复制
Contraction method will stop/delete the timer. 

感谢Pankaj

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-22 16:38:30

不应该发布NSTimer。它将通过触发invalidate来释放自身,删除行timerInterval = nil;,然后重试。我自己注意到的另一件事是:计时器应该总是由MainThread创建的,否则它不会开始执行。

//EDIT:尝试此代码以再次启动:

代码语言:javascript
运行
复制
// 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];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4507111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档