本文介绍: 本文简单节省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();

原文地址:https://blog.csdn.net/JH_Cao/article/details/122573345

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_39472.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注