iOS-定时器

2017-01-22  本文已影响0人  Tation

一.NSTimer

推荐亮点:

1.实用与图片轮播等频率不快的需求

相关操作:

1.暂停

[self.DD_Timer setFireDate:[NSDate distantFuture]];

2.继续执行

[self.DD_Timer setFireDate:[NSDate distantPast]];

3.关闭定时器

[self.DD_Timer invalidate];

self.DD_Timer = nil;

注意事项:

1.存在延迟可能性,精确时间在100ms左右

代码:

//实例化定时器

self.DD_Timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TimerFouncation) userInfo:nil repeats:YES];

//更改RunLoop运行模式,防止UIScrollView滚动时RunLoop模式改变,

[[NSRunLoop currentRunLoop]addTimer:self.DD_Timer forMode:NSRunLoopCommonModes];

//子线程运行循环需要手动开启

[[NSRunLoop currentRunLoop] run];

二.CADisplayLink

推荐亮点:

1.主要用于界面重绘,适合视频播放时获取下一帧进行界面渲染

相关操作:

1.preferredFramesPerSecond  用来设置间隔多少帧调用一次selector方法,默认值是0

2.duration 表示两次屏幕刷新之间的时间间隔,该属性在target的selector被首次调用以后才会被赋值,调用间隔时间 = duration × preferredFramesPerSecond

3.暂停

 self.DD_DisplayLink.paused = YES;

4.再次启用

self.DD_DisplayLink.paused = NO;

4.停止

[self.DD_DisplayLink invalidate];

self.DD_DisplayLink = nil;

注意事项:

1.延迟原因:当调用方法耗时,或者CPU忙碌程度高时,当次方法执行时间超过屏幕刷新周期,会导致跳过若干次执行机会

代码:

//需要手动添加到运行循环中,不然不会执行

self.DD_DisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(TimerFouncation)];

[self.DD_DisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

三.GCD定时器:

推荐亮点:

1.相对于NSTimer它可以直接在后台执行而不需要在main_queue和后台queue之间切换

2.精确度高,可达纳秒级

3.不需要添加到运行循环中

4.相对于NSTimer它立即执行block中的代码,NStimer需要等到第一次计时器触发

相关操作:

1.启用(激活):dispatch_resume(<#dispatch_object_t  _Nonnull object#>)

2.暂停(挂起):dispatch_suspend(<#dispatch_object_t  _Nonnull object#>)

3.停止:dispatch_source_cancel(<#dispatch_source_t  _Nonnull source#>)

注意事项:

1.dispatch_suspend定时器后不能释放,赋值为nil会导致崩溃

2.无法检测当前定时器是否处于挂起状态

代码:

1.系统自带提示:dispatch_source timer GCD

//************注意:timer 需要作为属性强引用,不然会被释放掉*****************//

dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());

dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer, ^{

[weakSelf TimerFouncation];

});

dispatch_resume(timer);

2.手动创建

//创建全局属性

@property (nonatomic, strong) dispatch_source_t DD_GCDTimer;

//block代码执行队列

dispatch_queue_t queue = dispatch_queue_create("queueName", DISPATCH_QUEUE_CONCURRENT);

self.DD_GCDTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

//定时器开启时间

dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));

//执行间隔

uint64_t interval = (uint64_t)(0.1 * NSEC_PER_SEC);

dispatch_source_set_timer(self.DD_GCDTimer, start, interval, 0);

__weak ViewController *weakSelf = self;

// 设置回调

dispatch_source_set_event_handler(self.DD_GCDTimer, ^{

[weakSelf GCDTimerFouncation];

});

// 启动定时器

dispatch_resume(self.DD_GCDTimer);

参考资料:

http://www.tuicool.com/articles/JN36BnY

http://blog.csdn.net/springjustin/article/details/50978671

上一篇 下一篇

猜你喜欢

热点阅读