iOS底层系列之<25>--Runloop<一>Runloop介绍

1、Runloop基本认识

  1. 每个程序都有一个Runloop,这个Runloop简单可以理解为一个死循环,目的是为了保证程序不会退出
  2. 每个程序的入口函数就会创建这个Runloop。
  3. Runloop中可以处理各种事件,触摸事件,点击事件,网络请求等。
  4. Runloop的好处可以节省CPU资源,休眠的时候就不会占用太多CPU资源。
int main(int argc, char * argv[]) {
    NSString * appDelegateClassName;
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}

伪代码可以转换为如下:

int main(int argc, char * argv[]) {
    NSString * appDelegateClassName;
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    int res = 0;
    do {
        int message = sleep();
        res = doSomething(message);
    } while (res== 0);
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}

2、Runloop对象

  1. iOS中有2套API来访问和使用Runloop
    Foundation: NSRunloop
    Core Foundation: CFRunloopRef
  2. NSRunloop是基于CFRunloopRef 的一层OC包装
  3. CFRunLoopRef是开源
  4. 重要点:CFRunLoop是纯C语言实现的,是线程安全的,NSRunloop非线程安全

获取Runloop对象

NSRunLoop *runloop = [NSRunLoop currentRunLoop];
CFRunLoopRef runloop2 = CFRunLoopGetCurrent();

在这里插入图片描述
可以看到,CFRunLoopRef的地址和NSRunLoop的_rl的地址指向是一样的

3、Runloop与线程

  1. 每条线程都有唯一的一个与之对应的Runloop对象
  2. Runloop保存在一个全局的Dictionary里,线程作为key,Runloop作为value
  3. 线程刚创建时并没有Runloop对象,Runloop会在第一次获取它时创建
  4. Runloop会在线程结束时销毁
  5. 主线程的Runloop已经自动获取(创建),子线程默认没有开启Runloop
  dispatch_async(<#dispatch_queue_t  _Nonnull queue#>, ^{
       // 子线程默认没有Runloop,除非手动调用
        [NSRunLoop currentRunLoop];
    });

获取当前线程Runloop和主线程Runloop

NSRunLoop *runloop = [NSRunLoop currentRunLoop];
NSRunLoop *runloop1 = [NSRunLoop mainRunLoop];
CFRunLoopRef runloop2 = CFRunLoopGetCurrent();
CFRunLoopRef runloop3 = CFRunLoopGetMain();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值