NSRunLoop 与 定时器
定时器的几种创建方式 和 类似的方式 :
A 这种方法是最常用的 但是 NSTimer 实现的定时器不精确,会受到当前线程上的其它操作的影响(且一般都是在
子线程中创建实现的,并且要用到 [[NSRunLoop currentRunLoop] run]; 目的是保证线程不被销毁,在
一直循环,可以让定时器一直用下去)
[NSTimer scheduledTimerWithTimeInterval:(调用的时间间隔) target:self
selector:@selector(调用的方法) userInfo:nil repeats:(是否重复调用)];
B // 自定义创建一个定时器
//(1)创建定时器 这种方式和 A 是一样的。(需要手动开启,当加入到runloop中后,就不需要手动操作了)
NSTimer *timer = [NSTimer timerWithTimeInterval:1
target:self
selector:@selector(repeatAction)
userInfo:nil
repeats:YES];
//(2)把定时器添加到当前的循环中(通过NSRunLoop去触发定时器事件)
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//(3)开启定时器
[timer fire];
C //60Hz 屏幕刷新率
//使用CADisplayLink对象,每次屏幕刷新,调用selector中的方法
//实现一个精确的定时器
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(调用的
方法)];
//也需要添加到 RunLoop 中,并选一种 默认的模式
[link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
C 这种方式是根据屏幕刷新的频率,这是手机硬件方面的,不受软件方面的影响,所以比 A B 两种方式更精确。
定时器的几种创建方式 和 类似的方式 :
A 这种方法是最常用的 但是 NSTimer 实现的定时器不精确,会受到当前线程上的其它操作的影响(且一般都是在
子线程中创建实现的,并且要用到 [[NSRunLoop currentRunLoop] run]; 目的是保证线程不被销毁,在
一直循环,可以让定时器一直用下去)
[NSTimer scheduledTimerWithTimeInterval:(调用的时间间隔) target:self
selector:@selector(调用的方法) userInfo:nil repeats:(是否重复调用)];
B // 自定义创建一个定时器
//(1)创建定时器 这种方式和 A 是一样的。(需要手动开启,当加入到runloop中后,就不需要手动操作了)
NSTimer *timer = [NSTimer timerWithTimeInterval:1
target:self
selector:@selector(repeatAction)
userInfo:nil
repeats:YES];
//(2)把定时器添加到当前的循环中(通过NSRunLoop去触发定时器事件)
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//(3)开启定时器
[timer fire];
C //60Hz 屏幕刷新率
//使用CADisplayLink对象,每次屏幕刷新,调用selector中的方法
//实现一个精确的定时器
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(调用的
方法)];
//也需要添加到 RunLoop 中,并选一种 默认的模式
[link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
C 这种方式是根据屏幕刷新的频率,这是手机硬件方面的,不受软件方面的影响,所以比 A B 两种方式更精确。