RunLoop与线程保活

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RunLoop与线程保活相关的知识,希望对你有一定的参考价值。

 代码:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, weak) NSThread *thread;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
    thread.name = @"My Thread";
    [thread start];
    
    self.thread = thread;
}

- (void)start {
    NSLog(@"%s - %@", __FUNCTION__, [NSThread currentThread].name);
    
    NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
    // Adds a port as an input source to the specified mode of the run loop
    [currentRunLoop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [currentRunLoop run];
}

- (void)run {
    NSLog(@"%s - %@", __FUNCTION__, [NSThread currentThread].name);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(run) onThread:self.thread withObject:nil waitUntilDone:NO];
}

@end

输出:

-[ViewController start] - My Thread
-[ViewController run] - My Thread
-[ViewController run] - My Thread
-[ViewController run] - My Thread

 

以上是关于RunLoop与线程保活的主要内容,如果未能解决你的问题,请参考以下文章

iOS 子线程用runloop保活的一个方案

你了解 RunLoop 线程保活吗?已封装好,2 句代码直接使用

『ios』根据runloop设计保活线程

runloop应用之iOS线程保活

RunLoop 实践

RunLoop总结:RunLoop的应用场景