1.
2、
#import "ViewController.h" @interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end @implementation ViewController -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self gcdTimer];
} /**
GCD定时器
*/
-(void)gcdTimer{ /**
DISPATCH_SOURCE_TYPE_TIMER 定时器
0 描述信息
0 更详细的描述信息
dispatchQueue : 队列决定定时器任务在哪个线程
*/
// dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, , , dispatch_get_global_queue(, )); /*
DISPATCH_TIME_NOW :起始时间
intervalInSeconds 间隔时间
leewayInSeconds 精准度, 绝对精准0
*/
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, * NSEC_PER_SEC, * NSEC_PER_SEC); /*
定时器任务
*/
dispatch_source_set_event_handler(timer, ^{
NSLog(@"=== %@", [NSThread currentThread]);
});
dispatch_resume(timer); /*
此时 定时器不会工作, 因为定时器有可能被释放掉了,异步线程和主线程都不会执行 ,需要强引用, strong,
GCD定时器是绝对精准的,拖拽tableview或者textview都会执行,NSTimer 分界面追踪模式和默认模式
*/ self.timer = timer;
} -(void)runloopTimer{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(runTimer) userInfo:nil repeats:YES];// 在主线程 // NSRunLoopCommonModes:会同时执行默认模式(NSDefaultRunLoopMode)和界面追踪模式(UITrackingRunLoopMode)
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode]; // 等价于 CFRunLoopAddTimer (参数1,参数2,参数3)
}
- (void)runloopTimer22{
NSRunLoop *runloop = [NSRunLoop currentRunLoop]; /**
默认是NSDefaultRunLoopMode
*/
[NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
[runloop run];
} -(void)runTimer{
NSLog(@"===%@====",[NSThread currentThread]);
} -(void)runLoop{
//主线程runloop
NSRunLoop *mainRunloop = [NSRunLoop mainRunLoop];
NSLog(@"mainRunloop =========== %p", mainRunloop);
// NSLog(@"mainRunloop 是个啥 === %@", mainRunloop);//打印一坨东西看不明白 //当前线程runloop
NSRunLoop * currentRunLoop = [NSRunLoop currentRunLoop];
NSLog(@"currentRunLoop ======== %p", currentRunLoop); //core
NSLog(@"CFRunLoopGetMain ====== %p", CFRunLoopGetMain());
NSLog(@"CFRunLoopGetCurrent === %p", CFRunLoopGetCurrent()); //转换
NSLog(@"mainRunloop.getCFRunLoop === %p", mainRunloop.getCFRunLoop);
NSLog(@"currentRunLoop .getCFRunLoop === %p", currentRunLoop.getCFRunLoop);
/*
2018-07-06 13:52:44.552563+0800 10 - runloop[12596:484429] mainRunloop =========== 0x6040000a2be0
2018-07-06 13:52:44.552908+0800 10 - runloop[12596:484429] currentRunLoop ======== 0x6040000a2be0
2018-07-06 13:52:44.553043+0800 10 - runloop[12596:484429] CFRunLoopGetMain ====== 0x6000001f3600
2018-07-06 13:52:44.553121+0800 10 - runloop[12596:484429] CFRunLoopGetCurrent === 0x6000001f3600
*/
} @end