前言:NStimer 创建有两种方式,一种是需要手动加入 RunLoop 中,另一种是默认帮你开启 RunLoop
一、手动开启 RunLoop
可以在当前线程指定哪个RunLoopMode中开启
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
二、自动开启 RunLoop
默认开启的 RunLoop 是在主线程 NSDefaultRunLoopMode
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];
三、子线程使用 NStimer(手动开启 RunLoop)
- 错误方法:
dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue1, ^{
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
});
注:上述代码不会执行!!!当 NStimer在主线程里添加时,主线程的 RunLoop
是默认执行的,但是子线程的RunLoop
是需要手动创建[NSRunLoop currentRunLoop]
和手动开启的[[NSRunLoop currentRunLoop] run];
。上述代码只是把 NStimer 添加到子线程的RunLoop
中,但并未开启当前RunLoop
。
- 正确方法:
dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue1, ^{
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
四、子线程使用 NStimer(自动开启 RunLoop)
自动开启的也要注意子线程RunLoop的创建和开启。
- 正确方法:
dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue1, ^{
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
});
网友评论