美文网首页
OC底层原理学习笔记(三)- Category

OC底层原理学习笔记(三)- Category

作者: hyq1101 | 来源:发表于2022-03-02 10:43 被阅读0次

一、Category的实现原理

1、Category编译之后的底层结构是 struct _category_t ,里面存储着分类的对象方法、类方法、属性、协议信息
#import "QLStudent+test.h"

@implementation QLStudent (test)

- (void)study {
    
}

+ (void)attendClass {
    
}

@end

将上述代码转成C++代码

Category编译之后的底层结构
struct _category_t {
    const char *name;
    struct _class_t *cls;
    const struct _method_list_t *instance_methods;
    const struct _method_list_t *class_methods;
    const struct _protocol_list_t *protocols;
    const struct _prop_list_t *properties;
};

// 与结构体 struct _category_t 中的成员一一对应
static struct _category_t _OBJC_$_CATEGORY_QLStudent_$_test __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "QLStudent",
    0, // &OBJC_CLASS_$_QLStudent,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_QLStudent_$_test,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_QLStudent_$_test,
    0,
    0,
};

// 分类中定义的对象方法
static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[1];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_QLStudent_$_test __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    1,
    {{(struct objc_selector *)"study", "v16@0:8", (void *)_I_QLStudent_test_study}}
};

// 分类中定义的类方法
static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[1];
} _OBJC_$_CATEGORY_CLASS_METHODS_QLStudent_$_test __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    1,
    {{(struct objc_selector *)"attendClass", "v16@0:8", (void *)_C_QLStudent_test_attendClass}}
};
2、在程序运行的时候,通过runtime动态将category的数据合并到类信息中(类对象、元类对象中)
源码 objc-runtime-new.mm
// 重新方法化
static void remethodizeClass(Class cls) 
{
    category_list *cats;
    bool isMeta;

    runtimeLock.assertWriting();

    isMeta = cls->isMetaClass();

    // Re-methodizing: check for more categories
    if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s", 
                         cls->nameForLogging(), isMeta ? "(meta)" : "");
        }
        // cls:类对象、元类对象
        // cats:分类列表
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}

// cls:类对象、元类对象
// cats:分类列表
static void 
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
    if (!cats) return;
    if (PrintReplacedMethods) printReplacements(cls, cats);
    // 判断是类对象还是元类对象
    bool isMeta = cls->isMetaClass();

    // fixme rearrange to remove these intermediate allocations
    // 方法数组
    method_list_t **mlists = (method_list_t **)
        malloc(cats->count * sizeof(*mlists));
    // 属性数组
    property_list_t **proplists = (property_list_t **)
        malloc(cats->count * sizeof(*proplists));
    // 协议数组
    protocol_list_t **protolists = (protocol_list_t **)
        malloc(cats->count * sizeof(*protolists));

    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int propcount = 0;
    int protocount = 0;
    int i = cats->count;
    bool fromBundle = NO;
    while (i--) {
        // 取出某个分类
        auto& entry = cats->list[i];
        // 取出分类中的对象方法或者类方法
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocols;
        if (protolist) {
            protolists[protocount++] = protolist;
        }
    }
    // 得到类对象或者元类对象里面的数据
    auto rw = cls->data();

    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    // 将所有分类的对象方法(类方法)附加到类对象(元类对象)的方法列表中
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);
    // 将所有分类的属性附加到类对象的属性列表中
    rw->properties.attachLists(proplists, propcount);
    free(proplists);
    // 将所有分类的协议附加到类对象的协议列表中
    rw->protocols.attachLists(protolists, protocount);
    free(protolists);
}

void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;

    if (hasArray()) {
        // many lists -> many lists
        uint32_t oldCount = array()->count;
        uint32_t newCount = oldCount + addedCount;
        // 扩容
        setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
        array()->count = newCount;
        // array()->lists 原来的方法列表
        // 将原来的方法列表移动到后面
        memmove(array()->lists + addedCount, array()->lists, oldCount * sizeof(array()->lists[0]));
        // addedLists 所有分类的方法列表
        // 将分类的方法列表拷贝到原来的方法列表的位置
        memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
    }
    else if (!list  &&  addedCount == 1) {
        // 0 lists -> 1 list
        list = addedLists[0];
    } 
    else {
        // 1 list -> many lists
        List* oldList = list;
        uint32_t oldCount = oldList ? 1 : 0;
        uint32_t newCount = oldCount + addedCount;
        setArray((array_t *)malloc(array_t::byteSize(newCount)));
        array()->count = newCount;
        if (oldList) array()->lists[addedCount] = oldList;
        memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
    }
}

Category的加载处理过程:
通过runtime加载某个类的所有Category数据
把所有Category的方法、属性、协议数据,合并到一个大数组中
后面参与编译的Category数据,会在数组的前面
将合并后的分类数据(方法、属性、协议),插入到类原来数据的前面
如果类、分类中有相同的方法,那么会先调用分类中的方法
多个分类的话会按后编译先调用

3、Category和Class Extension的区别是什么?

Class Extension在编译的时候,它的数据就已经包含在类信息中
Category是在运行时,才会将数据合并到类信息中

二、+load 方法

1、为什么类、分类里面的 +load 方法都会调用?

因为 +load 是通过函数指针直接调用

Runtime源码:objc-loadmethod.mm
// 调用类的 +load 方法
static void call_class_loads(void)
{
    int i;
    
    // Detach current loadable list.
    struct loadable_class *classes = loadable_classes;
    int used = loadable_classes_used;
    loadable_classes = nil;
    loadable_classes_allocated = 0;
    loadable_classes_used = 0;
    
    // Call all +loads for the detached list.
    for (i = 0; i < used; i++) {
        Class cls = classes[i].cls;
        // 取出类的 +load 方法的函数地址
        load_method_t load_method = (load_method_t)classes[i].method;
        if (!cls) continue; 

        if (PrintLoading) {
            _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
        }
        // 通过函数地址直接调用
        (*load_method)(cls, SEL_load);
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}

// 调用分类的 +load 方法
static bool call_category_loads(void)
{
    int i, shift;
    bool new_categories_added = NO;
    
    // Detach current loadable list.
    struct loadable_category *cats = loadable_categories;
    int used = loadable_categories_used;
    int allocated = loadable_categories_allocated;
    loadable_categories = nil;
    loadable_categories_allocated = 0;
    loadable_categories_used = 0;

    // Call all +loads for the detached list.
    for (i = 0; i < used; i++) {
        Category cat = cats[i].cat;
        // 取出某个分类的 +load 方法的函数地址
        load_method_t load_method = (load_method_t)cats[i].method;
        Class cls;
        if (!cat) continue;

        cls = _category_getClass(cat);
        if (cls  &&  cls->isLoadable()) {
            if (PrintLoading) {
                _objc_inform("LOAD: +[%s(%s) load]\n", 
                             cls->nameForLogging(), 
                             _category_getName(cat));
            }
            // 通过函数地址直接调用
            (*load_method)(cls, SEL_load);
            cats[i].cat = nil;
        }
    }
}
2、+load方法出现继承时的调用过程?
Runtime源码:objc-loadmethod.mm
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
        // 先调用类的 +load 方法
        while (loadable_classes_used > 0) {
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        // 再调用分类的 +load 方法
        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;
}

调用方式:+load 方法是通过函数指针直接调用
调用时刻:+load 方法会在runtime加载类、分类的时候调用,每个类、分类的 +load,在程序运行过程中只调用一次
调用顺序:
1> 先调用类的 +load
按照编译先后顺序调用(先编译,先调用)
调用子类的 +load 之前会先调用父类的 +load
2> 再调用分类的 +load
按照编译先后顺序调用(先编译,先调用)

三、+initialize 方法

Runtime源码:objc-runtime-new.mm
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    ......
    // 当前类需要初始化并且当前类还未初始化
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlockRead();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.read();
        // If sel == initialize, _class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172
    }

    ......
}
Runtime源码:objc-initialize.mm
/***********************************************************************
* class_initialize.  Send the '+initialize' message on demand to any
* uninitialized class. Force initialization of superclasses first.
**********************************************************************/
void _class_initialize(Class cls)
{
    assert(!cls->isMetaClass());

    Class supercls;
    bool reallyInitialize = NO;

    // Make sure super is done initializing BEFORE beginning to initialize cls.
    // See note about deadlock above.
    supercls = cls->superclass;
    // 如果存在父类,并且父类没有初始化,那就先初始化父类
    if (supercls  &&  !supercls->isInitialized()) {
        _class_initialize(supercls);
    }

    ......

    if (reallyInitialize) {

        ......

#if __OBJC2__
        @try
#endif
        {
            // 调用 +initialize 方法
            callInitialize(cls);

            if (PrintInitializing) {
                _objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
                             pthread_self(), cls->nameForLogging());
            }
        }
        ......
    }
    ......
}

// +initialize 方法最终是根据objc_msgSend进行调用的
void callInitialize(Class cls)
{
    ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
    asm("");
}

调用方式:+initialize 方法是通过objc_msgSend调用
调用时刻:+initialize方法会在类第一次接收到消息时调用
调用顺序:
1>先调用父类的 +initialize 方法,再调用子类的 +initialize 方法
2>先初始化父类,再初始化子类,每个类只会初始化1次
3>如果子类没有实现 +initialize,会调用父类的 +initialize(所以父类的 +initialize 可能会被调用多次)
4>如果分类实现了 +initialize,就覆盖类本身的 +initialize 调用

相关文章

网友评论

      本文标题:OC底层原理学习笔记(三)- Category

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