NSTimer創(chuàng)建分兩種情況:
1欠啤、通過(guò)
scheduledTimerWithTimeInterval
創(chuàng)建的NSTimer, 默認(rèn)就會(huì)添加到RunLoop的DefaultMode
中齐佳。
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
// 雖然默認(rèn)已經(jīng)添加到DefaultMode中, 但是我們也可以自己修改它的模式
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
2、通過(guò)
timerWithTimeInterval
和alloc
創(chuàng)建的NSTimer, 不會(huì)被添加到RunLoop的Mode中薪韩,我們要調(diào)用[[NSRunLoop currentRunLoop] addTimer:
方法霞篡。
_timer = [NSTimer timerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
_timer = [[NSTimer alloc]initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0] interval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"timer:%@",[NSThread currentThread]);
}];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
NSTimer執(zhí)行分兩種情況:
主線程:
NSRunLoop默認(rèn)開(kāi)啟噪裕,不用調(diào)用
[[NSRunLoop currentRunLoop] run];
NSLog(@"主線程:%@",[NSThread currentThread]);
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
子線程:
NSRunLoop需要自主開(kāi)啟铣猩,要調(diào)用
[[NSRunLoop currentRunLoop] run];
__weak typeof(self) weakSelf = self;
dispatch_queue_t queue = dispatch_queue_create("zixiancheng", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"子線程:%@",[NSThread currentThread]);
weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
[[NSRunLoop currentRunLoop] run];
});