iOS开发iOS Developer

iOS中的定时器

2016-07-17  本文已影响343人  落雪无痕_t

定时器是开发中常用一中工具,定时器常用的为NSTimer,CADisplayLink以及GCD定时器

/*
     第一个参数:时间间隔
     第二个参数:方法的调用者
     第三个参数:执行的方法
     最后一个参数:是否需要重复
     */
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(demo1) userInfo:nil repeats:YES];

注意:如果想要在有scrollView拖动的情况下定时器也能使用必须手动切换其运行模式到NSRunLoopCommonModes

//切换到NSRunLoopCommonModes
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
/*
     第一个参数:时间间隔
     第二个参数:方法的调用者
     第三个参数:执行的方法
     最后一个参数:是否需要重复
     */
    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(demo) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
 CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(demo)];
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

以下这幅图中可以看出CADisplayLink的执行频率
CADisplayLink的调用频率图:


Snip20160717_6.png

NSTimer的调用频率图:


Snip20160717_7.png
//创建
 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
//这里必须有一个强指针指向,因为GCD定时器本质还是一个OC对象
 self.timer = timer;
//设置定时器开始时间,这里的时间单位是纳秒
 dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW,2 * NSEC_PER_SEC);
//设置定时器
 dispatch_source_set_timer(timer,startTimer,(int64_t)(2 * NSEC_PER_SEC),0);
//设置定时器所做的事情,block回调
 dispatch_source_set_event_handler(timer,^{
 //定时器要做的事情
 });
//CGD定时器默认是暂停的,需要手动开启
 dispatch_resume(timer);
 //定时器的关闭
 dipatch_cancel(self.timer);
self.timer = nil

关于常用的定时器就介绍这么多,希望对大家有所帮助
作者:胥鸿儒

上一篇下一篇

猜你喜欢

热点阅读