主线程上的RunLoop运行循环

  • 主线程的消息循环是默认开启.
  • 在主线程中使用定时源.即定时器.
  • 步骤 : 将定时源添加到当前线程的消息循环.
 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     [self timerDemo];
 4 }
 5 
 6 - (void)timerDemo
 7 {
 8     // 提示 : 会自动的把timer添加到运行循环,默认是DefaultMode
 9     // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES];
10     
11     // 1.创建定时器 / 时钟 (timerWithTimeInterval : 不会自动的把timer添加到当前线程的运行循环)
12     NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES];
13     
14     // 2.获取当前主线程的运行循环,把定时器添加到当前主线程的运行循环;主线程的运行循环默认是开启的
15     // 2.1 forMode : 是timer的模式
16     // 2.2 消息循环也是要运行在某一特定的模式上的.只有输入事件的运行模式和消息循环的模式保持一致,那么消息循环才能检测到事件
17     // 2.3 NSRunLoop的默认模式也是`kCFRunLoopDefaultMode`;
18     // 2.4 当改变UI交互时,运行循环(NSRunLoop)的模式会自动的发生变化;  (模式要匹配)
19     // 2.5 NSRunLoopCommonModes : 是模式组,包含多种模式;kCFRunLoopDefaultMode 和 UITrackingRunLoopMode
20     // 2.6 UITrackingRunLoopMode : 追踪模式,专门为滚动视图的滚动事件设计的
21     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
22 }
23 
24 // 运行循环每隔一秒钟就检测一次这个方法,放在主线程执行
25 - (void)fireDemo
26 {
27     NSLog(@"hello %@",[NSRunLoop currentRunLoop].currentMode);
28 }

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值