- 主线程的消息循环是默认开启.
- 在主线程中使用
定时源
.即定时器
. - 步骤 : 将
定时源
添加到当前线程
的消息循环.
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 }