<span style="font-size:14px;"><strong>CADisplayLink 与 NSTimer 有什么不同</strong></span>
iOS设备的屏幕刷新频率是固定的,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高。
NSTimer的精确度就显得低了点,比如NSTimer的触发时间到的时候,runloop如果在阻塞状态,触发时间就会推迟到下一个runloop周期。并且 NSTimer新增了tolerance属性,让用户可以设置可以容忍的触发的时间的延迟范围。
CADisplayLink使用场合相对专一,适合做UI的不停重绘,比如自定义动画引擎或者视频播放的渲染。NSTimer的使用范围要广泛的多,各种需要单次或者循环定时处理的任务都可以使用。在UI相关的动画或者显示内容使用 CADisplayLink比起用NSTimer的好处就是我们不需要在格外关心屏幕的刷新频率了,因为它本身就是跟屏幕刷新同步的。
NSTimer初始化器接受调用方法逻辑之间的间隔作为它的其中一个参数,预设一秒执行30次。
CADisplayLink默认每秒运行60次,通过它的frameInterval属性改变每秒运行帧数,如设置为2,意味CADisplayLink每隔一帧运行一次,有效的逻辑每秒运行30次。
CADisplayLink
CADisplayLink *displaylink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateAttributedString)];
displaylink.paused = YES;
[displaylink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
NSTimer
float theInterval = 1.0 / 30.0f; //每秒调用30次
NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(updateAttributedString) userInfo:nil repeats:YES];
CADisplayLink 和 NSTimer
最新推荐文章于 2021-08-24 16:07:14 发布