Iphone 在viewcontroller中使用nstimer

Iphone 在viewcontroller中使用nstimer,iphone,Iphone,我有一个场景,我需要在点击按钮时启动/停止计时器。我可能会离开页面,然后再次返回,但计时器应该正在运行。为此,我将在ViewWillEnglish方法中停止并释放它,并根据ViewWillEnglishe中的条件重新启动它。但它不会再次开始。以下是我的代码: - (void)viewWillDisappear:(BOOL)animated { if([timerInterval isValid]) { [timerInterval invalidate]; //[timerInt

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

- (void)viewWillDisappear:(BOOL)animated {
if([timerInterval isValid]) {
    [timerInterval invalidate];
    //[timerInterval release];
    timerInterval = nil;
}
}

}

}

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

//编辑:请尝试此代码重新启动:

// 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];
}

你确定ViewWillAppeal确实再次被调用吗?是的,我已经用调试器检查过了…从主线程调用它是什么意思?你的意思是从应用程序委托调用它吗?如果你不知道主线程和后台线程之间的区别,那么你可能只使用主线程。(多线程)为了完整性,调用将是[self-performSelectorOnMainThread:withObject:waitUntilDone:]jep可能我的回答不够清楚,我不想说他必须删除该行。我目前不在实验室,无法测试,所以建议将其设置为零,也许会有帮助^^
-(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. 
// 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];
}