iOS 常驻线程

1.创建子线程并开启线程
2.给当前runloop添加port并运行runloop
3.将新任务添加到已休眠的线程

- (void)viewDidLoad {
  [super viewDidLoad];
  // 1.创建子线程并开启线程
  NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
  thread.name = @"myThread";
  [thread start];

  self.thread = thread;
}
- (void)run {
    NSLog(@"----------run----%@", [NSThread currentThread]);
  // 2.给当前runloop添加port并运行runloop
  NSRunLoop *cuttentRunLoop = [NSRunLoop currentRunLoop];
  [cuttentRunLoop addPort:[NSPort port] forMode:NSRunLoopCommonModes];
  [cuttentRunLoop run];

  //后面的都不是self.thread线程的事情 所以没有被打印 因为不会走到这一步 上面的一直在跑圈监听self.thread的线程
  NSLog(@"----------我没有被打印---------");
}

//当外界给这个正在RunLoo的线程一个外力时,也能够发送消息给test。因为self.thread线程没有消亡(RunLoop即使休眠了也会因为self.thread里有mode而不会消亡)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  //selector也是一个source
  [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- (void)test
{
   NSLog(@"----------test----%@", [NSThread currentThread]);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。