一.NSRunLoop的基本概念
- Run Loop 是线程相关的的基础框架的一部分。一个 run loop 就是一个事件处理 的循环,用来不停的调度工作以及处理输入事件。
- 线程的生命周期存在五个状态:新建、就绪、运行、阻塞、死亡
- NSRunLoop可以保持一个线程一直为活动状态,不会马上销毁掉。
二.定时器的普通使用与在线程中的使用
#import "ViewController.h"
@interface ViewController ()
{
int index;
int indexCount;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
index = 60;
//1 此方法是默认添加到当前的runloop中的
// [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];
//2
/*
//(1)创建定时器
NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];
//(2)把定时器对象添加到当前的runLoop中
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
//(3)开启定时器
[timer fire];
*/
//3 后台线程调用定时器
// [self performSelectorInBackground:@selector(backgroundTimer) withObject:nil];
//NStimer实现的定时器不是很准确,会受到当前线程中其他操作的影响
// long long j =0;
// for (long i =0; i<1000000000; i++) {
// j+=i;
// }
//屏幕刷新率 60HZ
//实现一个精确的定时器 (1/60s调用一次)
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(repeatAction)];
[link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//CADisplayLink 不受其他线程的影响
long long j =0;
for (long i =0; i<1000000000; i++) {
j+=i;
}
}
-(void)repeatAction{
indexCount++;
if (indexCount == 60) {
index--;
NSLog(@"index = %d",index)
indexCount= 0;
}
}
//后台线程调用的方法
-(void)backgroundTimer{
/*
(1) 主线程中的runloop默认是启动的,用于接收各种输入source
(2) 对于第二线程来说,runloop默认是没有启动的.
*/
//(1)创建timer (2)添加到当前的runloop (3)fire
[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];
//让当前runloop一直运行
//保证当前的线程不被销毁掉
[[NSRunLoop currentRunLoop] run];
//等效于:
// [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}