iOS Kitselector

iOS 底层原理-类的加载(下)

2021-01-05  本文已影响0人  远方竹叶

load_images

void
load_images(const char *path __unused, const struct mach_header *mh)
{
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories(); // 加载所有分类
    }

    // Return without taking locks if there are no +load methods here.
    if (!hasLoadMethods((const headerType *)mh)) return;

    recursive_mutex_locker_t lock(loadMethodLock);

    // Discover load methods // +load 方法
    {
        mutex_locker_t lock2(runtimeLock);
        prepare_load_methods((const headerType *)mh);
    }

    // Call +load methods (without runtimeLock - re-entrant)
    call_load_methods();
}

load_images 方法的主要作用是加载镜像文件,其中关键代码为 prepare_load_methods(加载)、call_load_methods(调用),两个方法

1. prepare_load_methods

void prepare_load_methods(const headerType *mhdr)
{
    size_t count, I;

    runtimeLock.assertLocked();

    classref_t const *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count); // 获取 Mach-O 中的静态段 __objc_nlclslist 即非懒加载类
    for (i = 0; i < count; i++) {
        // 将所有的 +load 方法与类绑定加入 loadable_classes 表中
        schedule_class_load(remapClass(classlist[i]));
    }

    // 获取 Mach-O 中的静态段 __objc_nlcatlist,即非懒加载分类,并 load 方法加入表中
    category_t * const *categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
    for (i = 0; i < count; i++) {
        category_t *cat = categorylist[I];
        Class cls = remapClass(cat->cls);
        
        if (!cls) continue;  // category for ignored weak-linked class
        if (cls->isSwiftStable()) {
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        realizeClassWithoutSwift(cls, nil);
        ASSERT(cls->ISA()->isRealized());
        add_category_to_loadable_list(cat);
    }
}
static void schedule_class_load(Class cls)
{
    if (!cls) return;
    ASSERT(cls->isRealized());  // _read_images should realize

    if (cls->data()->flags & RW_LOADED) return;

    // Ensure superclass-first ordering
    // 确保父类优先加载,递归,直到父类不存在
    schedule_class_load(cls->superclass);

    // 将所有的 +load 方法的类跟 load 方法绑定加入 loadable_classes 表中
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

其中,schedule_class_load(cls->superclass); 为了确保它的父类优先加载,是一层递归循环,直到根类(NSObject)的父类(nil)。add_class_to_loadable_list 是将类的 load 方法和 cls 类名一起加到 loadable_classes 表中,源码实现如下

void add_class_to_loadable_list(Class cls)
{
    IMP method;

    loadMethodLock.assertLocked();

    method = cls->getLoadMethod(); // 获取类的 load 方法
    if (!method) return;  // Don't bother if cls has no +load method
    
    if (PrintLoading) {
        _objc_inform("LOAD: class '%s' scheduled for +load", 
                     cls->nameForLogging());
    }
    
    if (loadable_classes_used == loadable_classes_allocated) { // 扩容
        loadable_classes_allocated = loadable_classes_allocated*2 + 16;
        loadable_classes = (struct loadable_class *)
            realloc(loadable_classes,
                              loadable_classes_allocated *
                              sizeof(struct loadable_class));
    }
    // 加入 loadable_classes 表中
    loadable_classes[loadable_classes_used].cls = cls;
    loadable_classes[loadable_classes_used].method = method;
    loadable_classes_used++;
}

获取类的 load 方法的源码如下

IMP 
objc_class::getLoadMethod()
{
    runtimeLock.assertLocked();
    const method_list_t *mlist;

    ASSERT(isRealized());
    ASSERT(ISA()->isRealized());
    ASSERT(!isMetaClass());
    ASSERT(ISA()->isMetaClass());

    mlist = ISA()->data()->ro()->baseMethods();
    if (mlist) {
        for (const auto& meth : *mlist) {
            const char *name = sel_cname(meth.name);
            if (0 == strcmp(name, "load")) {
                return meth.imp;
            }
        }
    }

    return nil;
}

通过获取 ro 中的方法列表,循环遍历,直到找到方法名为 loadsel,返回 load 的函数指针。

void add_category_to_loadable_list(Category cat)
{
    IMP method;

    loadMethodLock.assertLocked();

    method = _category_getLoadMethod(cat); // 获取分类的 load 方法

    // Don't bother if cat has no +load method
    if (!method) return;

    if (PrintLoading) {
        _objc_inform("LOAD: category '%s(%s)' scheduled for +load", 
                     _category_getClassName(cat), _category_getName(cat));
    }
    
    if (loadable_categories_used == loadable_categories_allocated) { // 扩容
        loadable_categories_allocated = loadable_categories_allocated*2 + 16;
        loadable_categories = (struct loadable_category *)
            realloc(loadable_categories,
                              loadable_categories_allocated *
                              sizeof(struct loadable_category));
    }

    // 添加到 loadable_categories 表中
    loadable_categories[loadable_categories_used].cat = cat;
    loadable_categories[loadable_categories_used].method = method;
    loadable_categories_used++;
}

2. call_load_methods

源码实现如下

void call_load_methods(void)
{
    static bool loading = NO;
    bool more_categories;

    loadMethodLock.assertLocked();

    // Re-entrant calls do nothing; the outermost call will finish the job.
    if (loading) return;
    loading = YES;

    void *pool = objc_autoreleasePoolPush();

    do {
        // 1. Repeatedly call class +loads until there aren't any more
        while (loadable_classes_used > 0) {
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        more_categories = call_category_loads();

        // 3. Run more +loads if there are classes OR more untried categories
    } while (loadable_classes_used > 0  ||  more_categories);

    objc_autoreleasePoolPop(pool);

    loading = NO;
}

从源码注释中可以看到,关键代码是在一个 do - while 循环中,主要有三个部分

call_class_loads 的源码实现如下

call_category_loads 的源码实现如下

call_class_loadscall_category_loads 中 load 消息发送 (*load_method)(cls, @selector(load)); 有两个隐藏参数,第一个为 id 即self,第二个为 sel,即 cmd

分类(category)与类扩展(extension)

Category 类别、分类

Extension 类扩展

类扩展的底层原理探索

创建方式有两种

选择 Extension 类型、选择要添加拓展的主类,创建

类扩展的本质

写一个类扩展,如下

通过 clang 底层编译探索

可以看到编译过程中生成了带下划线的成员变量以及 setter、getter 方法。再来看下类扩展中的方法

从上面我们可以得知,在编译的过程中,类扩展中的方法被添加到 methodlist 中成为了类的一部分,即编译时期直接添加到本类。

通过源码探索
/** ------.h ------*/
@interface LGPerson : NSObject

@end

/** ------.m ------*/
#import "LGPerson.h"
#import "LGPerson+Ext.h"

@implementation LGPerson

+ (void)load {
    
}

- (void)ext_instanceMethod {
    
}

- (void)ext_classMethod {
    
}

- (void)instanceMethod {
    
}

- (void)classMethod {
    
}

@end

/** ------ LGPerson+Ext.h ------*/
#import "LGPerson.h"

@interface LGPerson ()

@property (nonatomic, copy) NSString *lg_name;

- (void)ext_instanceMethod;
- (void)ext_classMethod;

@end

可以看到此时有四个方法,分别打印出来

可以看到此时打印的是 LGPerson.m 中实现的四个方法

按照上面的再来一次,看看此时的 ro 情况

方法列表中有 7 个方法,分别打印出来

此时在拓展类(LGPerson+Ext.h)声明的属性也实现 settergetter 方法以及一个 .cxx 方法

类的扩展在编译期间会作为类的一部分,和类一起编译进来
类的扩展只是声明,依赖于当前的主类,没有.m文件

上一篇 下一篇

猜你喜欢

热点阅读