0
点赞
收藏
分享

微信扫一扫

iOS底层系列之<29>--Runloop<五>Runloop中线程保活问题

1、普通情况下,子线程声明周期

- (void)run {
    NSLog(@"%s %@",__func__,[NSThread currentThread]);
    [[NSRunLoop currentRunLoop] run];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s",__func__);
    JHThread *thread = [[JHThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
}

打印结果:
在这里插入图片描述
为什么会这样?

第5点就阐述了原因了!

  • 改进方法1
- (void)run {
    NSLog(@"%s %@",__func__,[NSThread currentThread]);
    // 添加任一 Source0/Source1/Timer/Observer,即可保证Runloop不会立马退出
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}
  • 改进方法2
- (void)viewDidLoad {
    [super viewDidLoad];
    self.thread = [[JHThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [self.thread start];
}

// 真正要做事的函数
- (void)test {
    NSLog(@"%s",__func__);
}

// 这个方法的目的是为了线程保活
- (void)run {
    NSLog(@"%s %@",__func__,[NSThread currentThread]);
    // 添加任一 Source0/Source1/Timer/Observer,即可保证Runloop不会立马退出
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s",__func__);
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    NSLog(@"123");
    
}
举报

相关推荐

0 条评论