OC底层原理(五):Category实现原理

平时我们应该会比较常用分类,今天我们直接分析Category的本质原理,分析过后应该对于分类的大部分问题都能有一个自信的答案。

Category本质

我们已经OC中类的本质都是结构体,分类也不例外,也是结构体,直接上源码结构

struct category_t {
    const char *name; //类的名字
    classref_t cls;   //类
    struct method_list_t *instanceMethods; //实例方法的列表
    struct method_list_t *classMethods;//类方法的列表
    struct protocol_list_t *protocols; //协议的列表
    struct property_list_t *instanceProperties; //属性列表
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;

    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};

这里就是Category的真正结构,我们会发现它只有属性列表,没有成员变量。那么分类他的实现原理是什么呢?我们看下它编译之后的样子。
先创建这样一个分类

//Person+AddCategory.h
@interface Person (AddCategory)

@property(nonatomic, assign)int age;
- (void)eat;
- (void)run;
+ (void)live;
@end

//Person+AddCategory.m
@implementation Person (AddCategory)
- (void)eat{
    NSLog(@"category-eat");
}
- (void)run{
    NSLog(@"category-run");
}
+ (void)live{
    NSLog(@"category-live");
}
@end

我们通过clang编译一下这个.m文件

xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Person+AddCategory.m

在生产的.cpp文件中,我们可以找到这些代码
和源码中看到类似的结构体,这里只有主要的方法、协议、属性列表等信息

image.png

再向下看_method_list_t类型的结构体,下面={}中的结构和上面的定义结构一致,并且可以在里面看到我们在Category里面实现的对象方法。
image.png

还有一个_method_list_t,这里是类方法
image.png

下面是协议列表:
image.png

然后是属性列表:
image.png

后面是对一个新的_category_t类型的_OBJC_$_CATEGORY_Person_$_AddCategory结构体赋值,与_category_t结构体结构一致
image.png

最后,编译器在'__DATA'段下的__objc_catlist section里保存了一个大小为1的category_t的数组L_OBJC_LABEL_CATEGORY$(如果有多个category,会生成对应长度的数组),用于运行期category的加载。后面我们分析Category在运行时的加载。
image.png

Category加载

为了了解清楚分类在runtime到底是怎么加载的,我们直接看runtime源码,runtime初始化入口


image.png

方法调用顺序:进入map_images-->map_images_nolock-->_read_images
在_read_images方法里看到注释有 // Discover categories.
这里代码太长,不好截图(其实就是懒)

// Discover categories. 
    for (EACH_HEADER) {
        //获取分类列表
        category_t **catlist = 
            _getObjc2CategoryList(hi, &count);
        bool hasClassProperties = hi->info()->hasCategoryClassProperties();

        for (i = 0; i < count; i++) {
            category_t *cat = catlist[I];
            Class cls = remapClass(cat->cls);

            if (!cls) {
                // Category's target class is missing (probably weak-linked).
                // Disavow any knowledge of this category.
                catlist[i] = nil;
                if (PrintConnecting) {
                    _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
                                 "missing weak-linked target class", 
                                 cat->name, cat);
                }
                continue;
            }

            // Process this category. 
            // First, register the category with its target class. 
            // Then, rebuild the class's method lists (etc) if 
            // the class is realized. 
            bool classExists = NO;
            if (cat->instanceMethods ||  cat->protocols  
                ||  cat->instanceProperties) 
            {
                addUnattachedCategoryForClass(cat, cls, hi);
                if (cls->isRealized()) {
                    remethodizeClass(cls);
                    classExists = YES;
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category -%s(%s) %s", 
                                 cls->nameForLogging(), cat->name, 
                                 classExists ? "on existing class" : "");
                }
            }

            if (cat->classMethods  ||  cat->protocols  
                ||  (hasClassProperties && cat->_classProperties)) 
            {
                addUnattachedCategoryForClass(cat, cls->ISA(), hi);
                if (cls->ISA()->isRealized()) {
                    remethodizeClass(cls->ISA());
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category +%s(%s)", 
                                 cls->nameForLogging(), cat->name);
                }
            }
        }
    }

    ts.log("IMAGE TIMES: discover categories");

在这段代码中可以看到有获取分类列表catList,然后遍历里面的分类category_t *cat,然后关键位置,对象方法remethodizeClass(cls);类方法remethodizeClass(cls->ISA());
都是remethodizeClass()方法,我们再看这里的实现


image.png

再看attachCategories方法

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--) {//注意这里是倒叙遍历cat
        auto& entry = cats->list[i];
         //这里是给类中添加分类的对象方法还是元类中添加分类的类方法,都是走这里,我们暂时认为是给类中添加对象方法
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        //把分类中的对象方法列表放到mlists中
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }
        //把分类中的属性列表放到proplist中
        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }
         //把分类中的协议列表放到protolist中
        protocol_list_t *protolist = entry.cat->protocols;
        if (protolist) {
            protolists[protocount++] = protolist;
        }
    }
    //之前分析类结构的时候的class_rw_t结构体。
    auto rw = cls->data();
     //把mlists附加到class_rw_t中的methods上,attachLists(mlists, mcount)方法
    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);
    //把proplists附加到class_rw_t中的properties上,attachLists(proplists, propcount)方法
    rw->properties.attachLists(proplists, propcount);
    free(proplists);
     //把protolists附加到class_rw_t中的protocols上,attachLists(protolists, protocount)方法
    rw->protocols.attachLists(protolists, protocount);
    free(protolists);
}

这里总结:就是获取分类列表,然后倒叙遍历取出分类,然后将所有分类中的方法列表、属性列表、协议列表放到一个数组(二维数组:mlist、proplists、protolosts)中。
然后通过再通过对应结构的.attachLists方法附加到原来的类里的class_rw_t结构体的对应列表中。

这里还有比较关键的一点,attachLists方法的实现,看源码
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(内存起始位置)这块内存(大小是oldCount * sizeof(array()->lists[0]))移动到array()->lists + addedCount这个位置。
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            //关键,内存拷贝,将分类添加的列表数组addedLists(大小是addedCount * sizeof(array()->lists[0]))copy到array()->lists这个位置。
            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]));
        }
    }

这里主要的就是

  • memmove(array()->lists + addedCount, array()->lists, oldCount * sizeof(array()->lists[0]));
  • memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));

array()->lists是原列表数组,addedLists是分类添加的列表数组。首先是根据addedLists扩容,然后把原列表移动到列表最后,然后将addedLists添加到列表开头位置。

  • 这也就是为什么同样的方法名,分类的方法会覆盖原来类的方法(PS:并不是真正的覆盖,只是分类方法在原来类的方法列表的前面,在查找方法时,先查找到分类的方法就调用了,原来类的方法就不会被调用了)。
  • 那么问题又来了,多个分类分同样方法先调用谁的?我们注意一下分类在编译的时候编译完成就加入到catList中了,但是之前在遍历分类的时候是倒叙遍历的,所以也就是说后编译的分类最后attachCategories中组装的时候会在最前面,这也就可以解答这个问题。
  • 最后,编译顺序是什么样的呢?就是我们那在build Phases 中compile Source文件从上到下的顺序。
本来是有面试题的,后来发现了解这些后面试题就显得比较简单,有其他问题大家再一起讨论吧。有不对的请指出,一起学习,共勉!

文章编写参考MJ课程和iOS底层原理总结 - Category的本质

你可能感兴趣的:(OC底层原理(五):Category实现原理)