主线程和子线程中的消息循环

来源:互联网 发布:端口共享 编辑:程序博客网 时间:2024/04/23 21:41

RunLoop-主线程

主线程的消息循环是默认开启.在主线程中使用定时源.即定时器.步骤 : 将定时源添加到当前线程的消息循环.
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    [self timerDemo];}- (void)timerDemo{    // 创建定时器    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fire) userInfo:nil repeats:YES];    // 将定时器添加到消息循环    // currentRunLoop : 获取到当前的消息循环    // forMode : 当前定时源timer的运行模式    // NSRunLoopCommonModes : 模式组,里面包含了几种运行模式,kCFRunLoopDefaultMode / UITrackingRunLoopMode    // 消息循环也是运行在一个模式下面的,默认的模式是kCFRunLoopDefaultMode,只有定时源的运行模式和消息循环的运行模式保持一致,定时源对应的方法才能执行    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];}- (void)fire{    NSLog(@"hello %@",[NSRunLoop currentRunLoop].currentMode);}

RunLoop-子线程

子线程的消息循环是默认不开启.在子线程中使用定时源.即定时器.需要我们手动开启子线程的消息循环.步骤 : 将定时源添加到当前线程的消息循环.
- (void)viewDidLoad {    [super viewDidLoad];    [self performSelectorInBackground:@selector(timerDemo) withObject:nil];}/// 子线程执行的方法- (void)timerDemo{    // 创建定时器 (timer是个事件)    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES];    // 获取当前子线程的运行循环    // 提示 : 子线程的运行循环默认不开起;需要手动开启子线程的运行循环    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];    // 唯一需要掌握的一个概念 : 子线程的运行循环如果非要检测事件,必须手动开启运行循环    // 提示 : run (一旦调用了这个方法,运行循环就无法停止的,死循环)//    [[NSRunLoop currentRunLoop] run];    // 让运行循环只执行指定的时长    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];    // 运行循环执行结束之后,才能打印!!!    NSLog(@"如果开启消息循环使用的是run,那么我永远无法执行,run是一个死循环,只有上面的代码执行结束才能执行我呢");    NSLog(@"如果开启消息循环使用的是runUntilDate,那么只要它的时间到了,我就可以执行了,当前代码是3秒后执行");}- (void)fireDemo{    NSLog(@"hello");}
0 0
原创粉丝点击