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

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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zok93

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值