NSTimer不能在另一个线程中工作

ite*_*nyh 1 iphone multithreading objective-c

我有使用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];
    });

}
Run Code Online (Sandbox Code Playgroud)

我发现mainThread中的NSTimer工作但是另一个线程中的NSTimer不起作用.为什么会发生这种情况?我该如何解决这个问题?

Lil*_*ard 5

您不能在GCD队列上使用NSTimer.NSTimer需要NSRunLoop才能运行,而GCD队列则没有NSRunLoop.

如果您想要使用GCD队列的计时器功能,您应该使用dispatch_after()一次性计时器,或者使用dispatch_source重复计时器.