06、消息循环

1、什么是消息循环
1)RunLoop就是消息循环,每个线程内部都有一个消息循环

2)只有主线程的消息循环是默认是开启的,子线程的消息循环默认都不开启的


2、消息循环的目的
1)保证程序不退出

2)负责处理输入事件

3)如果没有任何时间发生,使程序处于休眠状态


3、消息循环的输入事件
Runloop接收输入事件来自于两种不同的源:
输入源(input source)
定时源(timer source)



4、消息循环的模式
1、NSDefaultRunLoopMode和UITrackingRunLoopMode

2、NSRunLoopCommonModes包含上面两种模式

3、使用注意
1)使用消息循环的时候必须指定两件事。
·输入事件:输入源或定时源
·消息循环模式

2)输入事件必须指定循环模式,如果想让输入事件在消息循环上执行,
那么输入事件的消息循环的模式必须和当前的消息循环的模式一致。

----------------------通过定时器演示消息循环start----------------------
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(demo) userInfo:nil repeats:YES];
//把定时器添加到当前线程消息循环中
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

//消息循环是在一个指定的模式下运行的 默认的模式NSDefaultRunLoopMode,设置的输入事件也需要指定一个模式,
//消息循环的模式必须和输入事件的模式匹配才会执行
// 当滚动scrollView的时候,消息循环的模式自动改变成UITrackingRunLoopMode
}

- (void)demo {
//输出当前消息循环的模式
NSLog(@"hello %@",[NSRunLoop currentRunLoop].currentMode);
}
----------------------通过定时器演示消息循环end------------------------


5、子线程的消息循环
1)主线程的消息循环是默认是开启的,子线程的消息循环默认是不开启的

2)启动子线程的消息循环
[[NSRunLoop currentRunLoop] run];

----------------------子线程开启消息循环演示start----------------------
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
//开启一个子线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];
[thread start];
//往子线程的消息循环中添加输入源
[self performSelector:@selector(demo1) onThread:thread withObject:nil waitUntilDone:NO];
}

//执行在子线程上的方法
- (void)demo {
NSLog(@"I'm running");
//开启子线程的消息循环,如果开启,消息循环一直运行
//当消息循环中没有添加输入事件,消息循环会立即结束
//[[NSRunLoop currentRunLoop] run];
//2秒钟之后消息循环结束
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
NSLog(@"end");
}

//执行在子线程的消息循环中
- (void)demo1 {
NSLog(@"I'm running on runloop");
}

@end
----------------------子线程开启消息循环演示end------------------------












猜你喜欢

转载自blog.csdn.net/daidaishuiping/article/details/80258603
今日推荐