美文网首页
对于OC中Category(分类)的加载时机、实现原理

对于OC中Category(分类)的加载时机、实现原理

作者: 再好一点点 | 来源:发表于2021-10-21 20:10 被阅读0次

一个类的分类是何时被载入内存的?分类中方法与对应类中的方法重名时调用此方法怎么执行?

想了解以上问题还需要查看objc源码才可以得到答案。下面就逐步揭开分类的面纱。为了更加直观还是直接贴一部分源码,源码里边会含有部分注释,然后最后总结。

分类数据结构如图:
category_数据结构.png

由上图可知分类无法直接添加成员变量,可以使用runtime的关联对象添加。

1. 首先找到dyld入口函数void _objc_init(void)
void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    runtime_init();
    exception_init();
#if __OBJC2__
    cache_t::init();
#endif
    _imp_implementationWithBlock_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

上述代码会调用_dyld_objc_notify_register(&map_images, load_images, unmap_image);这个函数。然后会分别依次调用load_imagesmap_images函数

2. 首先调用void load_images(const char *path __unused, const struct mach_header *mh)
void load_images(const char *path __unused, const struct mach_header *mh)
{
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories();
    }
  …...
}
3. static void loadAllCategories()
static void loadAllCategories() {
    mutex_locker_t lock(runtimeLock);

    for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
        load_categories_nolock(hi);
    }
}

调用load_images的时候通过loadAllCategories已经获取到了所有类的分类了。这个时候就可以执行map_images函数了。

4. 调用函数void map_images(unsigned count, const char * const paths[], const struct mach_header * const mhdrs[])
void map_images(unsigned count, const char * const paths[],
           const struct mach_header * const mhdrs[])
{
    mutex_locker_t lock(runtimeLock);
    return map_images_nolock(count, paths, mhdrs);
}
5. void map_images_nolock(unsigned mhCount, const char * const mhPaths[], const struct mach_header * const mhdrs[])
void map_images_nolock(unsigned mhCount, const char * const mhPaths[], const struct mach_header * const mhdrs[])
{
  ......
if (hCount > 0) {
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
    }
  ......
}
6. void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
  ......

// Discover categories. Only do this after the initial category
    // attachment has been done. For categories present at startup,
    // discovery is deferred until the first load_images call after
    // the call to _dyld_objc_notify_register completes. rdar://problem/53119145
    if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }
 ......
}
7. static void load_categories_nolock(header_info *hi)
static void load_categories_nolock(header_info *hi) {
  bool hasClassProperties = hi->info()->hasCategoryClassProperties();
  ......
 // 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()) {
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        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());
                    }
                }
    ......
}
8. 上述代码中调用了此函数static void attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count, int flags)。

1)其实以前版本的当前方法对分类排序是使用while循环来排序的,当前版本使用数组移动下标来实现了。
2)下面这段代码中含有部分注释请细看。

// 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.
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;
    method_list_t   *mlists[ATTACH_BUFSIZ];
    property_list_t *proplists[ATTACH_BUFSIZ];
    protocol_list_t *protolists[ATTACH_BUFSIZ];

    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    bool isMeta = (flags & ATTACH_METACLASS);
    auto rwe = cls->data()->extAllocIfNeeded();

    for (uint32_t i = 0; i < cats_count; i++) {
        auto& entry = cats_list[I];

        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            //默认一个类最多有64个分类,如果超过64个则先和合并一部分分类的方法,然后继续排序分类方法
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            
            //先读取到的分类方法列表放在mlists数组的后边,后读取到的分类方法列表放在mlists数组前边
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        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) {
        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();
            });
        }
    }

    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);

    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
9. void attachLists(List* const * addedLists, uint32_t addedCount)

1)此函数中的rwe属于类对象结构中的变量,里边存储了属性列表、协议列表、方法列表,他们数据类型又分别继承了list_array_tt这个类,所以都可以调用这个类list_array_tt里边的函数attachLists
2)以前版本这里合并属性、协议、方法这些列表是使用memmovememcpy实现的。当前版本使用修改数组下标实现了。
3)不明白类对象数据结构的请看这里
4)下面代码中含有注释,请细心查看。

 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;
            //原来数组扩容
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;
            
            //向后移动数组中原来的数据
            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) {
            // 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;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            for (unsigned i = 0; i < addedCount; I++)
                array()->lists[i] = addedLists[I];
            validate();
        }
    }
总结如下:

1)根据objc源码可以看到分类是在程序启动的dyld阶段加载进内存的。
_objc_init -> _dyld_objc_notify_register -> map_images -> map_images_nolock -> _read_images ->
load_categories_nolock -> attachCategories -> attachLists

2)由于最后加载(编译)的分类在方法合并进原类方法列表的时候放在了方法列表的最前边,所以调用同名方法的时候会调用最后加载(编译)的分类中的方法。

相关文章

网友评论

      本文标题:对于OC中Category(分类)的加载时机、实现原理

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