2012-07-07 79 views
0

我想在调用viewWillAppear方法时启动计时器。计时器无法启动viewWillAppear方法

它的工作完美,但当我在这个当前视图上推出一个新视图时,有一个问题,它已经有一个计时器。当我弹出新的视图并调用viewWillAppear时,我想再次启动计时器。我拥有大部分技术,但无法找到解决方案。

-(void)viewWillAppear:(BOOL)animated 
{ 
     [super viewWillAppear:animated]; 
     [NSThread detachNewThreadSelector:@selector(createTimer) toTarget:self withObject:self]; 
} 


- (void)createTimer 
{  
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 

    gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain]; 
    [[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode]; 
    timeCount = 360; 
    [runLoop run]; 
    [pool release]; 

} 

- (void)timerFired:(NSTimer *)timer 
{ 
    if(timeCount == 0) 
    { 
     [self timerExpired]; 
    } else { 
     timeCount--; 
     if(timeCount == 0) { 
      [timer invalidate]; 
      [self timerExpired]; 
     } 
    } 
    timeLabel.text = [NSString stringWithFormat:@"%02d:%02d",timeCount/60, timeCount % 60]; 
} 


- (void) timerExpired 
{ 
    //NSLog(@"Final == %@",arrayAnswers); 
    //NSLog(@"Attempt == %d",[arrayAnswers count]); 

    [gameTimer invalidate]; 
    gameTimer = nil; 
} 
+0

如果您[显示**代码的相关**部分](http://mattgemmell.com/2008/12/08/what-have-you-tried/)以便人们可以找出你的问题在哪里。 – Ben 2012-07-07 11:04:41

+0

你尝试过'[timer invalidate];'? – Bazinga 2012-07-07 11:10:02

+0

我尝试了所有可能的方式,但我仍然无法解决问题 – iDhaval 2012-07-07 11:15:51

回答

0

那么,根据经验,你的问题是计时器的线程。基本上,问题在这里:

[NSThread detachNewThreadSelector:@selector(createTimer) toTarget:self withObject:self]; 

我不是很确定,但我相信你的代码没有错。我还没有弄清楚,但我猜想在使用detachNewThreadSelector:时,NSTimer对象不会被激活。尝试在主线程上执行定时器。

[self performSelectorOnMainThread:@selector(createTimer) withObject:nil waitUntilDone:NO] 

我已经做到了这一点,并得到了我想要的结果。