定时器的几种使用方式。

1.NSTime

NSTime有2中常见的初始化方式,
第一种

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printCount) userInfo:nil repeats:YES];

这种初始化方式会对当前控制器强引用,所以在离开页面的时候一定要执行[self.timer invalidate];不然当前的Controller并不会销毁。(注:如果使用的是block的方法,Controller会销毁掉,但是定时器并不会销毁,而是一直在运行,所以也需要手动暂停)。

第二种方式是:

self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(printCount) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];

此种方式必须手动添加到runloop中才能执行,退出页面时也要调用[self.timer invalidate];不然当前的Controller并不会销毁。

self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(printCount)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

这个好像项目中基本不用。。。 http://www.jianshu.com/p/c35a81c3b9eb 可以看看这个。

GCD

NSTimeInterval period = 1.0; //设置时间间隔

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);   
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
        //在这里执行事件[
        [self printCount];
    });
dispatch_resume(_timer);


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    dispatch_cancel(_timer);
    _timer =nil;
}

GCD定时器可以不受runloop影响 比NSTimer更准确

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值