美文网首页
iOS底层原理——浅谈RunLoop

iOS底层原理——浅谈RunLoop

作者: yangfei02821 | 来源:发表于2020-07-05 11:49 被阅读0次
    RunLoop处理逻辑

    RunLoop应用:线程保活

    线程保活、控制销毁

    @interface ViewController ()
    @property (strong, nonatomic) MJThread *thread;
    @property (assign, nonatomic, getter=isStoped) BOOL stopped;
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        __weak typeof(self) weakSelf = self;
        
        self.stopped = NO;
        self.thread = [[MJThread alloc] initWithBlock:^{
            NSLog(@"%@----begin----", [NSThread currentThread]);
            
            // 往RunLoop里面添加Source\Timer\Observer
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            while (!weakSelf.isStoped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
            
            NSLog(@"%@----end----", [NSThread currentThread]);
            
            // NSRunLoop的run方法是无法停止的,它专门用于开启一个永不销毁的线程(NSRunLoop)
            //        [[NSRunLoop currentRunLoop] run];
            /*
             it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:.
             In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers
             */
        }];
        [self.thread start];
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    }
    
    // 子线程需要执行的任务
    - (void)test{
        NSLog(@"%s %@", __func__, [NSThread currentThread]);
    }
    
    - (void)stop {
        // 在子线程调用stop
        [self performSelector:@selector(stopThread) onThread:self.thread withObject:nil waitUntilDone:NO];
    }
    
    // 用于停止子线程的RunLoop
    - (void)stopThread{
        // 设置标记为NO
        self.stopped = YES;
        // 停止RunLoop
        CFRunLoopStop(CFRunLoopGetCurrent());
        NSLog(@"%s %@", __func__, [NSThread currentThread]);
    }
    

    iOS-浅谈RunLoop8
    iOS底层原理总结 - RunLoop
    基于runloop的线程保活、销毁与通信
    深入理解RunLoop

    相关文章

      网友评论

          本文标题:iOS底层原理——浅谈RunLoop

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