NSTimer没有开火

Ada*_*one 5 macos objective-c nstimer

对于我的生活,我无法弄清楚为什么这个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];
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了苹果文档和其他问题,但我无法弄清楚.它甚至没有打过timerDireMethod:一次电话.我听说这可能是由不同的线程引起的,但据我所知,我没有使用多个线程.

欢迎所有想法.

bne*_*ely 9

来自Mac OS X的NSTimer文档:

您必须使用addTimer:forMode:将新计时器添加到运行循环中.然后,在经过秒秒后,计时器将触发,将消息aSelector发送到目标.(如果计时器配置为重复,则无需随后将计时器重新添加到运行循环中.)

就个人而言,我通常使用 +[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

另请注意,如果在后台线程上调用此方法,或者在后台队列中运行的块操作中,则会NSTimer在后台线程执行时销毁.因此,请确保在主线程或主队列中运行它,以适合您的情况.