runloop在主线程里面是默认开启的,在子线程里是默认关闭的。
一、简介
首先,先象征性的讲下RunLoop的概念
从字面上看,就可以看出就是兜圈圈,就是一个死循环嘛。
二、作用
1.保持程序运行
2.处理app的各种事件(比如触摸,定时器等等)
3.节省CPU资源,提高性能。
2.RunLoop与线程
1.每条线程都有唯一的与之对应的RunLoop对象。
2.主线程的RunLoop已经创建好了,而子线程的需要手动创建。(也就是说子线程的RunLoop默认是关闭的,因为有时候开了个线程但却没有必要开一个RunLoop,不然反而浪费了资源。 )
3.RunLoop在第一次获取时创建,在线程结束时销毁。(这就相当于 线程是一个类,RunLoop是类里的实例变量,这样便于理解)
例子NSTimer的使用
在项目中用的NSTimer其实也和RunLoop有关系,下面我们来做个实验
实验一 scheduledTimer方法
修改一下button的响应以及timerTest方法,代码如下
- (IBAction)ButtonDidClick:(id)sender{
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
}
- (void)timerTest {
NSLog(@"timerTest----");
}
点击button可以看到输出台每隔一秒钟就打印"timerTest----"。
实验二 timerWithTime方法
代码如下
- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; } - (void)timerTest { NSLog(@"timerTest----"); }
但是实验结果是,点击button后没有反应。为什么呢?
噢~原来是少加了一句话,添加后的代码如下:
- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; } - (void)timerTest { NSLog(@"timerTest----"); }
可是,为什么实验二比实验一要多加一句话呢?解:那是因为scheduledTimer方法会自动添加到当前的runloop里面去,而且runloop的运行模式kCFRunLoopDefaultMode,也就是说实验一已经将timer自动加入到了一个运行模式为kCFRunLoopDefaultMode的runloop中。
实验三 有scrollView的情况下使用Timer
首先,按钮响应以及timerTest的方法如下:
- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; } - (void)timerTest { NSLog(@"timerTest----"); }