dispatch_after使用方法详解

来源:互联网 发布:vb wince 全屏 编辑:程序博客网 时间:2024/06/05 02:15
 dispatch_after能让我们添加进队列的任务延时执行,该函数并不是在指定时间后执行处理,而只是在指定时间追加处理到dispatch_queue
    该方法的第一个参数是time,第二个参数是dispatch_queue,第三个参数是要执行的block。
    dispatch_time_t有两种形式的构造方式,第一种相对时间:DISPATCH_TIME_NOW表示现在,NSEC_PER_SEC表示的是秒数,它还提供了NSEC_PER_MSEC表示毫秒。第二种是绝对时间,通过dispatch_walltime函数来获取,dispatch_walltime需要使用一个timespec的结构体来得到dispatch_time_t。
    以下代码可以很清楚地看到dispatch_after的执行效果,
    dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        NSLog(@"hello");
    });
    _count=1;
    _timer=[NSTimer timerWithTimeInterval:1 target:self selector:@selector(run) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];


  -(void)run
  {
    if (_count==10) {
        [_timer invalidate];
    }
    _count++;
    NSLog(@"the value is %d",_count);
}
result:
2014-12-26 20:30:19.549 testApp[24698:196764] the value is 2
2014-12-26 20:30:20.549 testApp[24698:196764] the value is 3
2014-12-26 20:30:21.549 testApp[24698:196764] the value is 4
2014-12-26 20:30:22.549 testApp[24698:196764] the value is 5
2014-12-26 20:30:23.549 testApp[24698:196764] the value is 6
2014-12-26 20:30:24.549 testApp[24698:196764] the value is 7
2014-12-26 20:30:25.548 testApp[24698:196764] the value is 8
2014-12-26 20:30:26.550 testApp[24698:196764] the value is 9
2014-12-26 20:30:27.550 testApp[24698:196764] the value is 10
2014-12-26 20:30:28.549 testApp[24698:196764] hello
2014-12-26 20:30:28.549 testApp[24698:196764] the value is 11