NSTimer和CADisplayLink的基本用法

本文深入探讨了iOS开发中NSTimer与CADisplayLink的使用场景与区别,包括它们的工作原理、核心参数以及如何在实际项目中应用。详细对比了这两者在背景计算、数据更新与画面动画中的角色,帮助开发者更好地选择合适的定时器来优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:  http://www.flakor.cn/2015-03-28-876.html?utm_source=tuicool

简要区别:
NSTimer初始化器接受调用方法逻辑之间的间隔作为它的其中一个参数,预设一秒执行30次。
CADisplayLink默认每秒运行60次,通过它的frameInterval属性改变每秒运行帧数,如设置为2,意味CADisplayLink每隔一帧运行一次,有效的逻辑每秒运行30次。
此外,NSTimer接受另一个参数是否重复,而CADisplayLink默认为重复,直到它失效。
还有一个区别在于,NSTimer一旦初始化它就开始运行,而CADisplayLink需要将显示链接添加到一个运行循环中,即用于处理系统事件的一个Cocoa Touch结构。
NSTimer 我们通常会用在背景计算,更新一些数值资料,而如果牵涉到画面的更新,动画过程的演变,我们通常会用CADisplayLink。

NSTimer

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
@interface ViewController : UIViewController
{
 
    NSTimer *theTimer; //声明
}
 
//使用
 
float theInterval = 1.0 / 30.0f;  //每秒调用30次
 
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(MyTask) userInfo:nil repeats:YES];
 
//停用
 
[theTimer invalidate];
theTimer = nil;

CADisplayLink,需要加入QuartzCore.framework及#import

/*CADisplayLink 默认每秒运行60次,将它的frameInterval属性设置为2,意味CADisplayLink每隔一帧运行一次,有效的使游戏逻辑每秒运行30次*/

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
    if(theTimer == nil)
 
    {
 
        theTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(MyTask)];
 
        theTimer.frameInterval = 2;
 
        [theTimer addToRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
 
    }
 
//停用
 
[theTimer invalidate];
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值