我希望在调用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 :(得分:0)
嗯,根据经验,你的问题是计时器的主题。基本上,问题出在这里:
[NSThread detachNewThreadSelector:@selector(createTimer) toTarget:self withObject:self];
我不是很确定,但我相信你的代码并没有错。我还没想出来但是我想在使用detachNewThreadSelector:
时没有激活NSTimer对象。尝试在主线程上执行计时器。
[self performSelectorOnMainThread:@selector(createTimer) withObject:nil waitUntilDone:NO]
我已经做到了,并得到了我想要的结果。