2012-07-07 31 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] 

我已經做到了這一點,並得到了我想要的結果。