NSTimer创建分两种情况:
1、通过
scheduledTimerWithTimeInterval
创建的NSTimer, 默认就会添加到RunLoop的DefaultMode
中。
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
// 虽然默认已经添加到DefaultMode中, 但是我们也可以自己修改它的模式
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
2、通过
timerWithTimeInterval
和alloc
创建的NSTimer, 不会被添加到RunLoop的Mode中,我们要调用[[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执行分两种情况:
主线程:
NSRunLoop默认开启,不用调用
[[NSRunLoop currentRunLoop] run];
NSLog(@"主线程:%@",[NSThread currentThread]);
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%@",[NSThread currentThread]);
}];
子线程:
NSRunLoop需要自主开启,要调用
[[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];
});