IOS GCD定時器

提到定時器,NStimer確定是咱們最爲熟悉的。oop

可是NStimer有着很大的缺點,並不許確。測試

通俗點說,就是它該作他的事了,可是因爲其餘事件的影響,Nstimer會放棄他應該作的。ui

而GCD定時器,是不會發生這種事情的。atom

GCD嚴格按照規定好的規格去作事。spa

前面介紹RunLoop 的時候已經介紹了NSTimer。code

這裏就不在介紹了。blog

在這裏着重介紹一下GCD定時器。隊列

首先,咱們知道NStimer是在RunLoop的基礎上執行的,然而RunLoop是在GCD基礎上實現的,因此說GCD可算是更加高級。事件

先看一下演示效果get

一些細節在代碼註釋中

//
//  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便可)

相關文章
相關標籤/搜索