首页 > 代码库 > RunLoop与线程保活
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与线程保活
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。