zoukankan      html  css  js  c++  java
  • iOS

    dispatch_after 是来延迟执行的GCD方法,因为在主线程中我们不能用sleep来延迟方法的调用,所以用dispatch_after是最合适的

    dispatch_after 能让我们添加进队列的任务延时执行,该函数并不是在指定时间后执行处理,而只是在指定时间追加处理到dispatch_queue

    GCD是Grand Central Dispatch的缩写,是苹果对多核硬件上执行并发代码的一种支持。

    它有以下优点:

    • GCD通过把计算密集型任务放于后台运行,以此提高APP的响应速度。
    • GCD提供了更简单的并发模型,它优于线程锁,并且帮助你避免并发bug。
    • GCD基于底层、高性能的优化常规类型的代码,例如单例。
    //该方法的第一个参数是 time,第二个参数是 dispatch_queue,第三个参数是要执行的block。
    //在主线程中延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      //Your code... });

    特别注意 : 上面这句 dispatch_after 的真正含义是在6秒后把任务添加进队列中,并不是表示在6秒后执行,大部分情况该函数能达到我们的预期,只有在对时间要求非常精准的情况下才可能会出现问题。

     

    参数dispatch_time_t解析

     

    dispatch_time_t 有两种形式的构造方式,第一种相对时间:通过 dispatch_time 函数。第二种是绝对时间,通过 dispatch_walltime 函数来获取,其需要使用一个 timespec 的结构体来得到dispatch_time_t

    dispatch_time(<#dispatch_time_t when#>, <#int64_t delta#>)
    
    //DISPATCH_TIME_NOW 表示现在,NSEC_PER_SEC 表示的是秒数,它还提供了 NSEC_PER_MSEC 表示毫秒
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC);   //10s 之后‘执行’(也就是上面说的加入到队列中)
    
    dispatch_walltime(<#const struct timespec * _Nullable when#>, <#int64_t delta#>)
    
    //要使用一个 timespec 的结构体
    dispatch_walltime(<#const struct timespec * _Nullable when#>, <#int64_t delta#>)
    dispatch_time_t time_w = dispatch_walltime(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);
    
    NSLog(@"——————————————————————————");
        //在主线程中延迟执行
    dispatch_after(time_w, dispatch_get_main_queue(), ^{
       NSLog(@"=======================");
    });

     

    解析dispatch_timedispatch_walltime

    dispatch_time stops running when your computer goes to sleep. dispatch_walltime continues running. So if you want to do an action in one hour minutes, but after 5 minutes your computer goes to sleep for 50 minutes, dispatch_walltime will execute an hour from now, 5 minutes after the computer wakes up. dispatch_time will execute after the computer is running for an hour, that is 55 minutes after it wakes up.


    dispatch_time 得到的时间长度是相对的,与设备 running 时间相关,即设备运行时才计时;而 dispatch_walltime 设定的时间段是绝对的,与设备是否running无关;

  • 相关阅读:
    40种网页常用小技巧(javascript)
    伸缩效果
    震动的超链
    一个模仿图片透明渐变做的表格颜色渐变效果
    荧 光 效 果
    用LoadRunner编写socket应用的测试脚本
    突发奇想写的一篇小科幻(如果可以叫做科幻的话)
    《软件性能测试过程详解与案例剖析》一书在Chinapub上8月份的销售排名持续上升
    建立高效的测试团队
    探索性测试(Exploratory Testing)概述
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10150572.html
Copyright © 2011-2022 走看看