下图是我整理的查看源码顺序

Untitled

我们可以运行源码,查看他的方法执行顺序加以验证

Untitled

在加载分类信息的过程中,核心处理主要在load_categories_nolock、attachCategories和attachLists方法中。

load_categories_nolock

static void load_categories_nolock(header_info *hi) {
    bool hasClassProperties = hi->info()->hasCategoryClassProperties();
 
    size_t count;
    /// C++ block
    auto processCatlist = [&](category_t * const *catlist) {
        for (unsigned i = 0; i < count; i++) {
            category_t *cat = catlist[i];
            Class cls = remapClass(cat->cls);
            locstamped_category_t lc{cat, hi};

            if (!cls) {
                // Category's target class is missing (probably weak-linked).
                // Ignore the category.
                if (PrintConnecting) {
                    _objc_inform("CLASS: IGNORING category \\?\\?\\?(%s) %p with "
                                 "missing weak-linked target class",
                                 cat->name, cat);
                }
                continue;
            }

            // Process this category.
            if (cls->isStubClass()) { //是否是基类rootClass
                // Stub classes are never realized. Stub classes
                // don't know their metaclass until they're
                // initialized, so we have to add categories with
                // class methods or properties to the stub itself.
                // methodizeClass() will find them and add them to
                // the metaclass as appropriate.
                if (cat->instanceMethods ||
                    cat->protocols ||
                    cat->instanceProperties ||
                    cat->classMethods ||
                    cat->protocols ||
                    (hasClassProperties && cat->_classProperties))
                {
                    objc::unattachedCategories.addForClass(lc, cls);
                }
            } else {
                // First, register the category with its target class.
                // Then, rebuild the class's method lists (etc) if
                // the class is realized.
                // 实例方法
                if (cat->instanceMethods ||  cat->protocols
                    ||  cat->instanceProperties)
                {
                    if (cls->isRealized()) {//若cls已经初始化了,则重新编译该类的方法列表
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        // 调用unattachedCategories 类的addForClass方法
                        // 注册分类并将其加入到当前class
                        objc::unattachedCategories.addForClass(lc, cls);
                    }
                }
                // 类方法
                if (cat->classMethods  ||  cat->protocols
                    ||  (hasClassProperties && cat->_classProperties))
                {
                    if (cls->ISA()->isRealized()) {
                        attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls->ISA());
                    }
                }
            }
        }
    };
    /// 执行block
    processCatlist(hi->catlist(&count));
    processCatlist(hi->catlist2(&count));
}

下面是是对attachCategories方法的分析。

// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
// 加载分类方法的核心操作
// cls:类对象 OR 元类对象,cats_list:分类列表
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
                 int flags)
{
    if (slowpath(PrintReplacedMethods)) {
        printReplacements(cls, cats_list, cats_count);
    }
    if (slowpath(PrintConnecting)) {
        _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
                     cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
                     cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
    }

    /*
     * Only a few classes have more than 64 categories during launch.
     * This uses a little stack, and avoids malloc.
     *
     * Categories must be added in the proper order, which is back
     * to front. To do that with the chunking, we iterate cats_list
     * from front to back, build up the local buffers backwards,
     * and call attachLists on the chunks. attachLists prepends the
     * lists, so the final result is in the expected order.
     */
    
    // 先分配固定内存空间来存放方法列表、属性列表和协议列表
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    // 对象方法列表 OR 类方法列表
    /*
    mlists 是一个二维数组
    [
     [category01_m_list], 第一个分类的方法列表category01_m_list: [method_t, method_t, method_t, ...]
     [category02_m_list], 第二个分类的方法列表category02_m_list: [method_t, method_t, method_t, ...]
    ]
    */
    method_list_t   *mlists[ATTACH_BUFSIZ];
    // 属性列表:是二维数组[[property_t, property_t, ....], [property_t, property_t, ....]]
    property_list_t *proplists[ATTACH_BUFSIZ];
    // 协议列表:是二维数组[[protocol_ref_t, protocol_ref_t, ....], [protocol_ref_t, protocol_ref_t, ....]]
    protocol_list_t *protolists[ATTACH_BUFSIZ];

    //用于记录操作次数,当等于64时会被置为 0
    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    // 是否是元类:YES 元类, NO 类
    bool isMeta = (flags & ATTACH_METACLASS);
    /*
     struct class_rw_ext_t {
         DECLARE_AUTHED_PTR_TEMPLATE(class_ro_t)
         class_ro_t_authed_ptr<const class_ro_t> ro;
         method_array_t methods;
         property_array_t properties;
         protocol_array_t protocols;
         char *demangledName;
         uint32_t version;
     } rwe;
     */
    auto rwe = cls->data()->extAllocIfNeeded();
    
    /// cats_count 分类总数
    for (uint32_t i = 0; i < cats_count; i++) {
        /// 获取分类
        auto& entry = cats_list[i];
        /// 得到分类的方法列表:isMeta YES 类方法列表,NO 实例方法列表
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) { /// 当mlists中存储了64个元素,就把对象/类方法添加到 cls 中
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            // cattegory 实例/类方法列表天机到mlists数组中
            // mcount = 0
            // ATTACH_BUFSIZ = 64
            // ATTACH_BUFSIZ - ++mcount = 63,以此推理,先编译的分类方法数组会放在mlists底部,所以最后编译的分类方法列表会放在整个方法列表大数组的最前面
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }
        // 同上面一样取出的是分类中的属性列表proplist加到大数组proplists中
        // proplists是一个二维数组:[[property_t, property_t, ....], [property_t, property_t, ....]]
        property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) {
                rwe->properties.attachLists(proplists, propcount);
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) {
                rwe->protocols.attachLists(protolists, protocount);
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }

    if (mcount > 0) {// 将剩余没有添加到cls 中的对象/类方法添加到 methods数组中
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        // 将分类的所有对象方法或者类方法,都附加到类对象或者元类对象的方法列表中
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }
    // 将分类的所有属性附加到类对象的属性列表中,这里运用了数组指针 运算操作,proplists + ATTACH_BUFSIZ - propcount,这个操作会把数组指针移动到未attach的位置
    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
    // 将分类的所有协议附加到类对象的协议列表中,这里运用了数组指针 运算操作,proplists + ATTACH_BUFSIZ - propcount,这个操作会把数组指针移动到未attach的位置
    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

下面是attachLists对方法的分析

void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;
    if (hasArray()) { // 存在数组
        // many lists -> many lists
        // 这里是把类的地址重新分配新的地址加 newCount 也是分类的创建个数,
        // 而老的分类信息重新复制一下内存,通过 i-- 倒着取值,所以最先编译的会在最后面,
        // 获取旧数组元素的个数
        uint32_t oldCount = array()->count;
        // 计算新数组的元素个数
        uint32_t newCount = oldCount + addedCount;
        // 重新分配内存空间,以newCount
        array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
        /// 将数组的count赋值为最新的值(newCount)
        newArray->count = newCount;
        /// 将旧的数组的count更新到最新的值(newCount)
        array()->count = newCount;
        
        /**
         * 递减遍历(从最大下标向最小坐标遍历),将就数组里的元素从后往前的依次放到新数组里
         * oldCount = 2
         * addedCount = 1;
         * newCount = 3;
         * newArray[3];
         * array()->lists[1] 放到 newArray->lists[1 + 1]
         * 就数组最后的一个元素,放到新数组的最后一个坐标,
         * 依次类推这里就可以说明最后编译的分类方法会被优先执行
         * array()->lists[0] 放到 newArray->lists[0 + 1]
         */
        for (int i = oldCount - 1; i >= 0; i--)
            newArray->lists[i + addedCount] = array()->lists[i];
        
        // 将新增加的元素从前往后的依次放到新数组里
        for (unsigned i = 0; i < addedCount; i++)
            newArray->lists[i] = addedLists[i];
        // 是否旧的数组
        free(array());
        // 赋值新数组数据
        setArray(newArray);
        validate();
    }
    else if (!list  &&  addedCount == 1) { //不存在旧数组 并且 添加 1 个新元素
        // 0 lists -> 1 list
        list = addedLists[0];
        validate();
    } 
    else { //其他情况
        // 1 list -> many lists
        Ptr<List> oldList = list;
        /// 旧数组元素个数
        uint32_t oldCount = oldList ? 1 : 0;
        /// 新数组元素个数
        uint32_t newCount = oldCount + addedCount;
        /// 重新分配内存空间,以newCount
        setArray((array_t *)malloc(array_t::byteSize(newCount)));
        array()->count = newCount;
        /// 如果存在旧数组,就把旧数组的元素放到数组的最后一个位置
        if (oldList) array()->lists[addedCount] = oldList;
        /// 将新元素从0到addedCount 依次添加到数组里
        for (unsigned i = 0; i < addedCount; i++)
            array()->lists[i] = addedLists[i];
        validate();
    }
}
  1. (hasArray())