1. NSRunLoop的基本概念(常用于定时器的不断运行)
(1).Run loops 是线程相关的基础框架的一部分。一个runloop就是一个事件处理的循环,用来不停的调度工作以及处理输入事件
(2).线程的生命周期存在五个状态:新建、就绪、运行、阻塞、死亡
(3).NSRunLoop可以保持一个线程一直为活跃状态,不会马上销毁掉。
示例:
在控制器的.h文件中中定义一个全局变量:int index;
在一个控制器的viewDidLoad方法中:
-(void)viewDidLoad{
[super viewDidLoad];
[selfperformSelectorInBackground: @selector(MultiThread) withObject:nil];
}
-(void)multiThread{
//启动定时器
@autoreleasepool{
[NSTimerscheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
//获得当前的runloop
[[NSRunLoop currentRunLoop] run];
}
}
-(void) timerActionL(NSTimer*)timer{
index++;
NSLog(@”定时器打印!”);
if(index == 20){
//停止定时器
[timer invalidate];
}
}
运行结果将是不停的循环执行timerAction,直到index等于20.
2.定时器在主线程阻塞时会可能不准确,所以要提高定时器的准确度,应该尽量在多线程中使用定时器而不是在主线程中