提到定時器,NStimer肯定是我們最為熟悉的。 但是NStimer有著很大的缺點,並不准確。 通俗點說,就是它該做他的事了,但是由於其他事件的影響,Nstimer會放棄他應該做的。 而GCD定時器,是不會發生這種事情的。 GCD嚴格按照規定好的規格去做事。 前面介紹RunLoop 的時候已經介紹了 ...
提到定時器,NStimer肯定是我們最為熟悉的。
但是NStimer有著很大的缺點,並不准確。
通俗點說,就是它該做他的事了,但是由於其他事件的影響,Nstimer會放棄他應該做的。
而GCD定時器,是不會發生這種事情的。
GCD嚴格按照規定好的規格去做事。
前面介紹RunLoop 的時候已經介紹了NSTimer。
這裡就不在介紹了。
在這裡著重介紹一下GCD定時器。
首先,我們知道NStimer是在RunLoop的基礎上執行的,然而RunLoop是在GCD基礎上實現的,所以說GCD可算是更加高級。
先看一下演示效果
一些細節在代碼註釋中
// // ViewController.m // CX GCD 定時器 // // Created by ma c on 16/3/30. // Copyright © 2016年 xubaoaichiyu. All rights reserved. // #import "ViewController.h" NSInteger count = 0; @interface ViewController () //註意**這裡不需要✳️號 可以理解為dispatch_time_t 已經包含了 @property (nonatomic, strong)dispatch_source_t time; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"歡迎來到旭寶愛吃魚的博客"); //獲得隊列 dispatch_queue_t queue = dispatch_get_global_queue(0, 0); //創建一個定時器 self.time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); //設置開始時間 dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)); //設置時間間隔 uint64_t interval = (uint64_t)(2.0* NSEC_PER_SEC); //設置定時器 dispatch_source_set_timer(self.time, start, interval, 0); //設置回調 dispatch_source_set_event_handler(self.time, ^{ NSLog(@"旭寶愛吃魚"); //設置當執行五次是取消定時器 count++; if(count == 5){ dispatch_cancel(self.time); } }); //由於定時器預設是暫停的所以我們啟動一下 //啟動定時器 dispatch_resume(self.time); } @end
在前面說了,GCD是不會發揮不穩定的因此我們測試一下,在這裡我們演示一下,就不展示代碼了
(添加一個TextView即可)