子线程上的RunLoop运行循环

  • 子线程的消息循环是默认不开启.
  • 在子线程中使用定时源.即定时器.需要我们手动开启子线程的消息循环.
  • 步骤 : 将定时源添加到当前线程的消息循环.
 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     [self performSelectorInBackground:@selector(timerDemo) withObject:nil];
 4 }
 5 
 6 - (void)timerDemo
 7 {
 8     NSLog(@"begin");
 9     
10     // 1.创建定时器
11     NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES];
12     
13     // 2.把定时器添加到当前子线程的运行循环(子线程的运行循环默认不开启)
14     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
15     
16     // 3.手动开启子线程的运行循环 (这个是主线程的运行循环和子线程的运行循环唯一的不同点)
17     // run : 一旦调用这个方法开启子线程的运行循环,就不会停止
18     // 一旦开启运行循环,相当于就开启了死循环
19     [[NSRunLoop currentRunLoop] run];
20     
21     // runUntilDate : 让子线程的运行循环,只执行指定的时间
22     // [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];
23     
24     // 永远不会执行,因为runUntilDate没有打开,
25     NSLog(@"end");
26 }
27 
28 - (void)fireDemo
29 {
30     NSLog(@"hello");
31 }

 

 

问题:子线程消息循环开启后,后面的代码不会执行,主线程怎么可以?

答:主线程的消息循环是默认开启的,就是用来处理UI交互的。

转载于:https://www.cnblogs.com/panda1024/p/6278238.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值