zoukankan      html  css  js  c++  java
  • iOS开发RunnLoop学习二:GCD中的定时器

    #import "ViewController.h"
    
    @interface ViewController ()
    /** 注释 */
    @property (nonatomic, strong) dispatch_source_t timer;
    @end
    
    @implementation ViewController
    /**
     * 1:GCD中的定时器:GCD中的定时器不受NSRanLoop影响 2:必须有强引用,引用该timer,要不,在方法执行完毕后timer就会被销毁,所以就不能执行定时器的任务,所以必须设置强引用timer,来保住timer的命来执行任务(因为其timer的定时器任务,不会立即执行,会间隔一段时间执行)
     *
     */
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"%s",__func__);
        
        
        //1.创建GCD中的定时器
        /*
         第一个参数:source的类型DISPATCH_SOURCE_TYPE_TIMER 表示是定时器
         第二个参数:描述信息,线程ID
         第三个参数:更详细的描述信息
         第四个参数:队列,决定GCD定时器中的任务在哪个线程中执行
         */
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
        
        //2.设置定时器(起始时间|间隔时间|精准度)
        /*
         第一个参数:定时器对象
         第二个参数:起始时间,DISPATCH_TIME_NOW 从现在开始计时
         第三个参数:间隔时间 2.0 GCD中时间单位为纳秒
         第四个参数:精准度 绝对精准0
         */
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        
        //3.设置定时器执行的任务
        dispatch_source_set_event_handler(timer, ^{
            NSLog(@"GCD---%@",[NSThread currentThread]);
        });
        
        //4.启动执行
        dispatch_resume(timer);
        
        self.timer = timer;
    }
    @end
  • 相关阅读:
    CF896C Willem, Chtholly and Seniorious 珂朵莉树
    LG2495 「SDOI2011」消耗战 虚树
    20191102 「HZOJ NOIP2019 Round #12」20191102模拟
    LG1345 「USACO5.4」Telecowmunication 最小割
    LG1344 「USACO4.4」Pollutant Control 最小割
    POJ1741 Tree 点分治
    [BZOJ2143]飞飞侠 并查集优化最短路
    [NOI.AC#41]最短路 线性基
    [NOI.AC#40]Erlang
    [BZOJ2238]Mst 最小生成树+树链剖分/并查集
  • 原文地址:https://www.cnblogs.com/cqb-learner/p/5859743.html
Copyright © 2011-2022 走看看