来自二级NSThread的NSTimer不起作用

时间:2014-12-31 13:05:48

标签: ios objective-c macos cocoa

根据Run Loop的文档,如果有任何输入源,NSThread将会运行,否则它将进入休眠状态。我配置的定时器与"配置定时器源"在上面的链接,但它没有触发。我正在使用下面的代码。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [NSThread detachNewThreadSelector:@selector(testOnThread) toTarget:self withObject:nil];
}

- (void) testThread
{

    NSLog(@"Test");
}


-(void)testOnThread
{
    @autoreleasepool {

        NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];

        // Create and schedule the first timer.
        NSDate* futureDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
        NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:futureDate
                                                    interval:0.1
                                                      target:self
                                                    selector:@selector(testThread)
                                                    userInfo:nil
                                                     repeats:YES];
        [myRunLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];
    }
}

以上代码从不打印"测试"。

但是如果我将[[NSRunLoop currentRunLoop] run];放在-(void)testOnThread方法的末尾,那么计时器每次都会触发它正常工作(Stackoverflow Question)。我的查询是,如果我们已经提供了计时器输入源来运行循环而不是使用[[NSRunLoop currentRunLoop] run];明确启动它的需要

1 个答案:

答案 0 :(得分:1)

我会让其他人回答你为什么必须自己run运行循环的问题。但是我想建议一个替代方案:

如果你想在后台线程上运行计时器,使用调度计时器是最简单的,恕我直言,根本不需要运行循环。只需定义计时器属性:

@property (nonatomic, strong) dispatch_source_t timer;

然后安排计时器在自定义队列上运行:

dispatch_queue_t queue = dispatch_queue_create("com.domain.app.timer", 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 20ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer, ^{
    // code to be performed periodically on background thread here
});

dispatch_resume(self.timer);