NSTimer
[NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"打印");
}];
- NSDefaultRunLoopMode 和 UITrackingRunLoopMode
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"打印");
}];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
- 或者直接设置NSRunLoopCommonModes标记
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
线程保活
@interface CRThread : NSThread
@end
@implementation CRThread
- (void)dealloc
{
NSLog(@"%s",__FUNCTION__);
}
@end
@interface RunloopController ()
@property(nonatomic,strong)CRThread *thread;
@property(nonatomic,assign)BOOL isStopRunloop;
@end
@implementation RunloopController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.isStopRunloop = NO;
[self.thread start];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self performSelector:@selector(doSomething) onThread:self.thread withObject:nil waitUntilDone:YES];
}
-(void)doSomething
{
NSLog(@"做任务 - %@",[NSThread currentThread]);
}
-(void)exitRunloop
{
self.isStopRunloop = YES;
CFRunLoopStop(CFRunLoopGetCurrent());
}
#pragma mark - lazy load
- (CRThread *)thread
{
if (!_thread) {
__weak typeof(self) weakSelf = self;
_thread = [[CRThread alloc] initWithBlock:^{
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
while (weakSelf && (weakSelf.isStopRunloop == NO)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
NSLog(@"退出Runloop");
}];
}
return _thread;
}
-(void)dealloc
{
[self performSelector:@selector(exitRunloop) onThread:self.thread withObject:nil waitUntilDone:YES];
NSLog(@"%s",__FUNCTION__);
}
@end