iOS-定時器的使用

一、NSTimer的使用

- (void)createNSTimer
{
    // 調用創建方法後,target對象的計數器會加1,直到執行完畢,自動減1。如果是循環執行的話,就必須手動關閉,否則可以不執行釋放方法
    // 必須進行停止 —— 釋放 [_timer invalidate];
    // 自動把timer加入MainRunloop的NSDefaultRunLoopMode中
#if 0
    _GZDTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(Logs) userInfo:nil repeats:YES];
#endif
    // 這種方法需要手動添加到NSDefaultRunLoopMode runloop的運行循環中,否則無法運行
    _GZDTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(Logs01) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_GZDTimer forMode:NSDefaultRunLoopMode];
}
- (void)Logs
{
    NSLog(@"NSTimer 自動運行循環  >>>>>>>");
}
- (void)Logs01
{
    NSLog(@"NSTimer 手動運行循環  >>>>>>>");
}

二、CADisplayLink的使用

// 使用CADisplayLink需要記得停止定時器,停止的方法
    // 停止displayLink的定時器
    //[self.displayLink invalidate];
    //self.displayLink = nil;

- (void)createCADisplayLink
{
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(GZDDisplayLink)];
    // NSInteger類型的值,用來設置間隔多少幀調用一次selector方法,默認值是1,即每幀都調用一次。
    
    // readOnly的CFTimeInterval值,表示兩次屏幕刷新之間的時間間隔。需要注意的是,該屬性在target的selector被首次調用以後纔會被賦值。selector的調用間隔時間計算方式是:調用間隔時間 = duration × frameInterval。
    
    /**當把CADisplayLink對象add到runloop中後,selector就能被週期性調用,類似於重複的NSTimer被啓動了;執行invalidate操作時,CADisplayLink對象就會從runloop中移除,selector調用也隨即停止,類似於NSTimer的invalidate方法。**/
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)GZDDisplayLink
{
    NSLog(@"GZDDisplayLink >>>>>>> ");
}

三、GCD

- (void)createGCD
{
    /**
     *  只執行一次
     */
#if 0
    double delayInSeconds = 2.0;//兩秒後,執行一次
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //執行事件
        NSLog(@"只執行一次>>>>>>>");
        });
#endif
    
    NSTimeInterval timerInterval = 1.0; //設置時間間隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // _timer必須爲全局變量
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), timerInterval * NSEC_PER_SEC, 0); //每秒執行
    dispatch_source_set_event_handler(_timer, ^{
        //在這裏執行事件
        NSLog(@"GCD -----  1s執行一次  >>>>>>>");
    });
    dispatch_resume(_timer);
}

詳細的源碼可以去我的github下載參考
https://github.com/daniel1214/160829-TimeUser

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章