美文网首页
iOS底层原理--Runloop

iOS底层原理--Runloop

作者: LoveToday2020 | 来源:发表于2020-06-26 23:55 被阅读0次

所谓的Runloop其实就是死循环
总共有5种模式

每条线程都有一个runloop 但是默认够不开启循环

作用
a. 保证Runloop 所在线程不退出
b. 负责监听事件iOS触摸、时钟、网络等

模式

a. Runloop模式 2020-06-26 下午10.31.47.png

UI与默认模式同时出现的时候,UI模式的优先级更高

将 NSTimer 添加到Runloop
a. NSDefaultRunLoopMode 默认模式
b. UITrackingRunLoopModel UI模式
c. NSRunLoopCommonModes 占位模式 (UI&默认)
例子
当页面有滚动视图时

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong)NSThread *thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.thread = [[NSThread alloc] initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    }];
    [self.thread start];
}

- (void)timerAction
{
    NSLog(@"timer action");
}

@end

Source事件源
按照函数调用栈
souce0: 非source1就是
souce1: 系统内核事件

GCD包装成的source

#import "SecondController.h"

@interface SecondController ()
@property(nonatomic, strong)dispatch_source_t timer;
@end

@implementation SecondController

- (void)viewDidLoad {
    [super viewDidLoad];
    // GCD timer
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    
    //设置定时器各种属性
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0);
    // 设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"-----%@", [NSThread currentThread]);
    });
    
    // 启动timer
    dispatch_resume(self.timer);
    
}

@end

Observe 观察者

参照git一个例子

https://github.com/LoveToday/Runloop-test.git

相关文章

  • Runloop

    Runloop 实现原理及应用iOS - RunLoop 底层源码详解及具体运用

  • RunLoop

    详细文章 xx_cc - iOS底层原理总结 - RunLoop 意一ineyee - RunLoop RunLo...

  • 探寻RunLoop的本质

    iOS底层原理总结 - RunLoop 面试题 讲讲 RunLoop,项目中有用到吗? RunLoop内部实现逻辑...

  • iOS底层原理——浅谈RunLoop

    RunLoop应用:线程保活 线程保活、控制销毁 iOS-浅谈RunLoop8iOS底层原理总结 - RunLoo...

  • RunLoop相关

    iOS底层原理总结 - RunLoop解密 Runloop Runloop是一种在当前线程,持续调度各种任务的运行...

  • Today面试

    Runloop 底层原理Kvo 底层原理ARC 底层原理 如何实现GCD 底层原理Block 底层原理Aut...

  • iOS底层原理-Runloop

    Runloop Runloop作用: 保持程序的持续运行 处理程序的各种事件(触摸事件、定时器事件等) 节约CPU...

  • 【iOS 底层原理】Runloop

    一. RunLoop简介 运行循环,在程序运行过程中循环做一些事情,如果没有Runloop程序执行完毕就会立即退出...

  • iOS底层原理 - RunLoop

    序言:关于RunLoop简书有很多技术牛人已经讲述的很详细了,而且不管是项目中或是工作中都会使用到,这段时间看了M...

  • iOS底层原理--Runloop

    所谓的Runloop其实就是死循环总共有5种模式 每条线程都有一个runloop 但是默认够不开启循环 作用a. ...

网友评论

      本文标题:iOS底层原理--Runloop

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