对于我的生活,我无法弄清楚为什么这个 NSTimer 不会触发。这是所有看起来相关的代码(至少对我而言)
- (IBAction)connectClick:(id)sender
{
if (connected)
{
NSLog(@"Disconnecting");
[timer invalidate];
timer = nil;
connected = NO;
[Connect setStringValue:@"Connect"];
NSLog(@"Finished\n");
}
else
{
NSLog(@"Connecting");
timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
//[timer fire]; tested this line. same results
[Connect setStringValue:@"a"];
connected = YES;
NSLog(@"Finished\n");
}
}
- (void)timerFireMethod:(NSTimer*)theTimer
{
NSLog(@"Fireing event");
//[self resetRequest];
//[spinner startAnimation:nil];
//[request startAsynchronous];
}
我已经阅读了 apple 文档和其他问题,但我无法弄清楚。它甚至不会调用 timerDireMethod:
一次。我听说这可能是由不同的线程引起的,但据我所知,我没有使用多线程。
欢迎所有想法。
最佳答案
来自 NSTimer documentation对于 Mac OS X:
You must add the new timer to a run loop, using addTimer:forMode:. Then, after seconds seconds have elapsed, the timer fires, sending the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)
就个人而言,我通常使用 +[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
另请注意,如果您在后台线程上或在后台队列中运行的 block 操作中调用此方法,NSTimer
会在后台线程执行时被销毁。因此,如果适合您的情况,请确保在主线程或主队列中运行它。
关于objective-c - NSTimer 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9347061/