0

我想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;
}
4

1 回答 1

0

好吧,根据经验,您的问题是计时器的线程。基本上,问题出在这里:

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

我不确定,但我相信您的代码并没有真正错误。我还没有弄清楚,但我猜 NSTimer 对象在使用时没有被激活detachNewThreadSelector:。尝试在主线程上执行计时器。

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

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

于 2012-07-08T17:28:03.290 回答