子线程上的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