2012-05-30 28 views
1

我有一个问题关于使用的NSTimer和代码如下工作,我已经简化了代码:的NSTimer不会在另一个线程

- (void) mainThreadFun 
{ 
    [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(test) userInfo:nil repeats:YES]; 

    dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
      [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(test1) userInfo:nil repeats:YES]; 
    }); 

} 

我发现的NSTimer在mainThread工作,但的NSTimer中另一个线程没有工作。为什么会发生这种情况,我该如何解决这个问题?

+0

可能的重复[如何在后台线程上创建NSTimer?](http://stackoverflow.com/questions/8304702/),[线程和NSTimer问题](http://stackoverflow.com/问题/ 3335114 /),[在NSThread中运行计时器](http://stackoverflow.com/questions/2083737/),[Threaded NSTimer](http://stackoverflow.com/questions/3156452/),[NSThread和NSTimer](http://stackoverflow.com/questions/1338891/) –

回答

5

您不能在GCD队列上使用NSTimer。 NSTimer需要运行一个NSRunLoop,并且GCD队列没有NSRunLoop。

如果您希望使用GCD队列的定时器功能,则应该使用dispatch_after()作为单次计时器,或者使用dispatch_source作为重复计时器。

+0

@JacquesCousteau:这是不正确的。队列不会被runloops耗尽。唯一的例外是主循环会排空主队列。你很困惑,因为调用'+ [NSRunLoop currentRunLoop]'实际上会为当前线程创建一个不存在的线程。但这并不意味着runloop实际上在运行,因为它不是。 –

+0

@JacquesCousteau:那么无论你是在主队列还是文档都是错误的。尝试在调试器中暂停并查看回溯。 NSRunLoop无处可寻。 –

+0

@JacquesCousteau:顺便说一句,如果你在全局队列上使用'dispatch_sync()'来测试这个,你可能会自欺欺人。 'dispatch_sync()'通常会在当前线程上运行该块(如果可以的话)。 –