#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)btnClick:(id)sender {
NSLog(@"--BtnClick---");
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// [self timer2];
[self performSelectorInBackground:@selector(timer2) withObject:nil];
// NSLog(@"%@",[NSRunLoop mainRunLoop]);
}
-(void)timer1
{
NSLog(@"---start---");
//1.创建定时器
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(operation1) userInfo:nil repeats:YES];
//2.添加定时器到当前的runloop中
/*
第一个参数:定时器对象
第二个参数:runloop的运行模式
*/
//[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//UITrackingRunLoopMode:把定时器添加到runloop中,并制定了运行模式.只有当runloop处于UITrackingRunLoopMode模式的时候,定时器才能工作
// [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
//NSRunLoopCommonModes:意味着把定时器添加到所有被标记为CommonModes的运行模式下面
/*
common modes = <CFBasicHash 0x7f84e8501810 [0x1073437b0]>{type = mutable set, count = 2,
entries =>
0 : <CFString 0x1081cea40 [0x1073437b0]>{contents = "UITrackingRunLoopMode"}
2 : <CFString 0x107363b40 [0x1073437b0]>{contents = "kCFRunLoopDefaultMode"}
}
*/
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)timer2
{
//不需要添加到runloop中
//该方法内部先创建一个定时器,会把定时器添加到当前线程所在的runloop中,制定运行模式为默认
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(operation1) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
//开启子线程对应的runloop
[[NSRunLoop currentRunLoop] run];
//注意:
//如果是子线程那么需要手动创建子线程对应的runloop
//子线程对应的runloop还需要开启
}
-(void)operation1
{
NSLog(@"---1---%@",[NSRunLoop currentRunLoop].currentMode);
}
@end