objective-c - NSTimer 不触发

标签 objective-c macos 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];
}

我已经阅读了 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/

相关文章:

ios - 错误的接收器类型 'CGImageRef'(又名 'CGImage *')

xcode - 在 OSX 上的 Swift 中使用 setFrameOrigin 将 NSView 添加到 super View 后居中

ios - 在前台和后台无限运行任务

macos - 致命的 : could not parse HEAD Error When Committing

xcode - Sigabrt swift Xcode(制作计时器)

iphone - IOS接收数据超时CFsocket

objective-c - 拖动 View

objective-c - 属性不使用点表示法?

iphone - 从设备中检索序列号

keyboard-shortcuts - 在 debian 上但在 Mac OS X 上,option/alt + 左/右箭头的等价物是什么?