美文网首页
iOS 常驻线程

iOS 常驻线程

作者: KevinChein | 来源:发表于2020-07-06 11:06 被阅读0次

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]);
}

相关文章

  • iOS:常驻线程

    常驻线程基本的思路都是等待信号>收到信号>执行回调>继续等待信号,在项目开发中需要将一些耗时的,不紧要的任务放到常...

  • iOS 常驻线程

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

  • iOS 常驻线程

    开启线程需要占用一定的内存空间(默认的情况下,主线程占1M,子线程占用512KB)且每次开辟子线程都会消耗CPU。...

  • iOS RunLoop(一)

    级别: ★★☆☆☆标签:「iOS」「RunLoop」「线程常驻」作者: 陈彬审校: QiShare团队 前言:这篇...

  • iOS RunLoop

    RunLoop 应用:NSTimer、 PerformSelector、常驻线程iOS 中有两套API访问 Fo...

  • iOS 创建常驻线程

    最近看了一些关于常驻线程的文章,发现了一些问题,写此文章记录一下,如果有写的不对的地方,欢迎大神指出... 常驻线...

  • iOS RunLoop常驻线程

    常驻线程的作用: 让一个一直存在的子线程,等待其他线程发来消息,处理其他事件。 1.设置成全局的,如果是线程对象是...

  • iOS 创建常驻线程

    iOS中默认就有个主线程即mainThread,我们的UI线程指的就是主线程,一般都是在主线程中操作UI,从某个角...

  • iOS GCD常驻线程

    - (void)viewDidLoad { [super viewDidLoad]; [self perf...

  • iOS面试问题

    一: iOS常驻线程 二: AFNetWorking 2.0与3.0的区别 三: 当开的后台线程太多, 如何进行内...

网友评论

      本文标题:iOS 常驻线程

      本文链接:https://www.haomeiwen.com/subject/gsfwqktx.html