Category的实现原理

  • Category编译后,其本质是结构体struct _category_t,里面存储着对象方法、类方法、属性、协议等信息
  • 程序运行时,runtime会将Category的数据合并到对应的类(类对象、元类对象)中
  • 调用顺序:如果多个category中的方法同名,将调用后编译的category中的方法。如果category和类中的方法同名,调用category中的方法。

struct _category_t

Category其实就是结构体,我们可以在终端中运行以下命令
xcrun -sdk iphones clang -arch arm64 -rewrite-objc -o <输出文件.cpp>
通过将OC代码转换为C\C++代码来证明。
创建一个ZJSPerson类的Category,

@implementation ZJSPerson (Test)
-(void)test{
    NSLog(@"ZJSPerson (Test) test");
}
@end

在终端输入xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc ./ZJSPerson+Test.m -o test.cpp,打开输出的test.cpp文件,搜索_category_t就可以找到以下两段代码,分别是_category_t的定义,以及根据源文件初始化了一个名为_OBJC_$_CATEGORY_ZJSPerson_$_Test结构体 。

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;
};
// 初始化_category_t的一个实例
static struct _category_t _OBJC_$_CATEGORY_ZJSPerson_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "ZJSPerson",
    0, // &OBJC_CLASS_$_ZJSPerson,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test,
    0,
    0,
    0,
};

由于ZJSPerson (Test)中只有一个实例方法,所以在初始化的时候除了类名字,只有 instance_methods有值,其他传的都是0。
接下来我们再来看一下一个稍微复杂一点的Category,其中包含了实例方法、类方法、属性、协议。

// ZJSPerson+Test2.h
@interface ZJSPerson (Test2)
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *name;
@end

#import "ZJSPerson+Test2.h"
@implementation ZJSPerson (Test2)
- (void)setAge:(NSInteger)age{}
- (NSInteger)age{
    return 0;
}
-(void)setName:(NSString *)name{ 
}
- (NSString *)name{
    return nil;
}
- (void)run{}
- (void)eat{}
+ (void)test1{}
+ (void)test2{}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    return nil;
}
@end

将其转化为cpp文件后,还是搜索_category_t,就可以找到_category_t的定义,以及初始化这个Category实例的地方。

static struct _category_t _OBJC_$_CATEGORY_ZJSPerson_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "ZJSPerson",
    0, // &OBJC_CLASS_$_ZJSPerson,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test2,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_ZJSPerson_$_Test2,
    (const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_ZJSPerson_$_Test2,
    (const struct _prop_list_t *)&_OBJC_$_PROP_LIST_ZJSPerson_$_Test2,
};

可以看到这次实例的名字变为了_OBJC_$_CATEGORY_ZJSPerson_$_Test2,初始化它的参数也变多了。
具体的参数详情在cpp文件中也都可以看到。
例如下面的就是实例方法列表

static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[7];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    7,
    {{(struct objc_selector *)"setAge:", "v24@0:8q16", (void *)_I_ZJSPerson_Test2_setAge_},
    {(struct objc_selector *)"age", "q16@0:8", (void *)_I_ZJSPerson_Test2_age},
    {(struct objc_selector *)"setName:", "v24@0:8@16", (void *)_I_ZJSPerson_Test2_setName_},
    {(struct objc_selector *)"name", "@16@0:8", (void *)_I_ZJSPerson_Test2_name},
    {(struct objc_selector *)"run", "v16@0:8", (void *)_I_ZJSPerson_Test2_run},
    {(struct objc_selector *)"eat", "v16@0:8", (void *)_I_ZJSPerson_Test2_eat},
    {(struct objc_selector *)"copyWithZone:", "@24@0:8^{_NSZone=}16", (void *)_I_ZJSPerson_Test2_copyWithZone_}}
};

由此课件Category的本质就是一个结构体struct _category_t。每一个Category都是它的一个实例,存储着对象方法、类方法、属性、协议等信息。

runtime将Category合并到对应的类

我们可以通过查看源码来了解runtime是如何将Category合并到对应的类。由于源码版本较多,我下载的是此时最新的版本objc4-781.tar.gz,不同版本可能存在一些差异。
下面是源码查看的顺序

objc-os.mm

  1. void _objc_init(void)

objc-runtime-new.mm

  1. map_images
  2. _read_images(Called by: map_images_nolock)
  3. realizeClassWithoutSwift
  4. methodizeClass
  5. attachToClass
  6. attachCategories
  7. attachLists

为了便于理解主要看attachCategoriesattachLists这两个方法。
有下面的两个方法课件,所有category方法的会组成一个二维数组,然后将这个数组添加到类的方法列表当中。
数组的顺序是类自身的方法在最后面,后加载(编译)的category在前,所以调用方法的时候先调用最后加载的category中的方法。如果category中的方法和类中的重复,则将调用category中的方法

// 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;
    // 数组,每个元素保存了一个category中的所有方法,相当于二维数组
    method_list_t   *mlists[ATTACH_BUFSIZ]; 
    // 数组,每个元素保存了一个category中的所有属性,相当于二维数组
    property_list_t *proplists[ATTACH_BUFSIZ];
    //  数组,每个元素保存了一个保存category中的所有协议,相当于二维数组
    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) {
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
                // 如果category的数量超过了 ATTACH_BUFSIZ 这个容量,则先添加一部分
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            // 从后向前,填充数组,先编译的在后,后编译的在前
            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) {
        // 添加剩余的category到类中
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount, NO, fromBundle);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) flushCaches(cls);
    }

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

    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
// 将保存了category方法的二维数组,添加到类的方法列表当中
// 类自身的方法在最后面,后加载的category在前,所以调用方法的时候先调用最后加载的category中的方法
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;
            // 将原来的数据(类自身的方法)移动到最后 
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            // 将保存了category方法的二维数组,添加到类的方法列表当中
            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的实现原理)