使用GCD运行重复NSTimer? [英] Run repeating NSTimer with GCD?

查看:104
本文介绍了使用GCD运行重复NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么当你在GCD块中创建一个重复的计时器,它不能工作?

I was wondering why when you create a repeating timer in a GCD block it doesen't work?

这很好:

-(void)viewDidLoad{
    [super viewDidLoad];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
}
-(void)runTimer{
    NSLog(@"hi");
}

但这项工作:

dispatch_queue_t myQueue;

-(void)viewDidLoad{
    [super viewDidLoad];

    myQueue = dispatch_queue_create("someDescription", NULL);
    dispatch_async(myQueue, ^{
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
    });
}
-(void)runTimer{
    NSLog(@"hi");
}


推荐答案

NSTimers 安排在当前线程的运行循环。但是,GCD分派线程没有运行循环,因此GCD块中的调度计时器不会执行任何操作。

NSTimers are scheduled on the current thread's run loop. However, GCD dispatch threads don't have run loops, so scheduling timers in a GCD block isn't going to do anything.

有三种合理的替代方法:

There's three reasonable alternatives:


  1. 弄清楚你想要计划什么运行循环,明确这样做。使用 + [NSTimer timerWithTimeInterval:target:selector:userInfo:repeats:] 创建计时器,然后 - [NSRunLoop addTimer:forMode :] ,以便在要使用的运行循环上实际计划它。这需要在运行循环上有一个句柄,但您可以使用 + [NSRunLoop mainRunLoop] 如果您想在主线程上执行此操作。

  2. 切换到使用基于计时器的调度源。这会在GCD感知机制中实现一个计时器,该计时器将以您选择的队列上的间隔运行一个块。

  3. 显式地 dispatch_async() 返回到主队列,然后创建计时器。这相当于使用主运行循环的选项#1(因为它也将在主线程上创建计时器)。

  1. Figure out what run loop you want to schedule the timer on, and explicitly do so. Use +[NSTimer timerWithTimeInterval:target:selector:userInfo:repeats:] to create the timer and then -[NSRunLoop addTimer:forMode:] to actually schedule it on the run loop you want to use. This requires having a handle on the run loop in question, but you may just use +[NSRunLoop mainRunLoop] if you want to do it on the main thread.
  2. Switch over to using a timer-based dispatch source. This implements a timer in a GCD-aware mechanism, that will run a block at the interval you want on the queue of your choice.
  3. Explicitly dispatch_async() back to the main queue before creating the timer. This is equivalent to option #1 using the main run loop (since it will also create the timer on the main thread).

当然,这里真正的问题是,为什么你从GCD队列创建一个定时器开始?

Of course, the real question here is, why are you creating a timer from a GCD queue to begin with?

这篇关于使用GCD运行重复NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆