美文网首页iOS开发笔记
iOS Category的使用及原理

iOS Category的使用及原理

作者: Hello小小酥 | 来源:发表于2019-01-25 19:00 被阅读69次

  Category是我们在开发中经常用到的,它可以在我们不改变原有类的前提下来动态地给类添加方法,通过这篇文章,我们一起来了解一下Category。
下面我们列一下本文目录,以方便了解本文的主要内容。

  • Category的介绍
  • Category中的数据结构
  • Category的原理
  • Category的使用
  • Category和Extension的区别

Category的介绍

  Category是Objective-C 2.0之后添加的语言特性,它可以在不改变或不继承原类的情况下,动态地给类添加方法。我们平常说的分类或者类别就是说的Category。

Category中的数据结构

Category定义的源码我们可以在runtime的源码中找到,我们先来看一下Category的定义:

///runtime.h
/// An opaque type that represents a category.
typedef struct objc_category *Category;
struct objc_category {
    ///Category名称
    char * _Nonnull category_name                            OBJC2_UNAVAILABLE;
    ///类名
    char * _Nonnull class_name                               OBJC2_UNAVAILABLE;
    ///实例方法列表
    struct objc_method_list * _Nullable instance_methods     OBJC2_UNAVAILABLE;
    ///类方法列表
    struct objc_method_list * _Nullable class_methods        OBJC2_UNAVAILABLE;
    ///协议列表
    struct objc_protocol_list * _Nullable protocols          OBJC2_UNAVAILABLE;
}    

  通过定义我们可以看到,Category是指向objc_category结构体的指针,而objc_category结构体中包含了当前Category的名称(category_name)、类名称(class_name)、实例方法列表(instance_methods)、类方法列表(class_methods)、协议列表(protocols),我们看到objc_category结构体的定义中并没有属性列表,这也就是为什么我们用Category不能给类添加实例变量的原因。

Category的原理

  Category既然可以动态的给类添加方法,那么它的方法又是在什么时候添加的?把方法添加到哪里面去了呢?我们在调用Category中方法的时候又是怎样调用的呢?下面我们通过分析Category的源码来看一下它是怎样运行的。
  因为我们是在runtime的源码中找到Category的源码的,那么我们猜想Category中的方法是不是在运行时添加的呢?下面我们看一下它的源码:
Category在objc-runtime-new.h中的定义是category_t结构体。在查找Category执行时后我并不知道该如何查起,所以我就在objc-runtime-new.mm搜了一下category_t,我在2703行发现这样一段代码,并有说明:

    ///runtime.h
    // Discover categories. 
    for (EACH_HEADER) {
        category_t **catlist = 
            _getObjc2CategoryList(hi, &count);
        bool hasClassProperties = hi->info()->hasCategoryClassProperties();

通过注释我们知道在这发现了categories,当时我觉得这个方法应该就是,然后我就看了一下这个方法,发现这正是Category中的方法添加。在这里也给大家提供一个比较笨的方法,当我们查看源码时,只知道方法或者结构体的定义时,可以在当前的类中搜索,由于C语言的方法定义问题(方法的声明必须在调用之前,否则会因为没定义方法而报错,这里它并不像我们OC中的方法定义一样,可以在任意地方定义,在任意地方调用,C语言的方法定义必须在调用之前定义好,否则会提示方法没有定义而报错),我们都可以很容易的在当前文件中找到,而且源码中的注释写的也很明白。下面我们分析一下这段代码:

    ///runtime.h
    // 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);
                }
            }
        }
    }

首先我们看到的是一个for循环,而for循环的单次表达式、表达式和末尾循环体是一个EACH_HEADER宏,我们找到该宏的定义:

#define EACH_HEADER \
    hIndex = 0;         \
    hIndex < hCount && (hi = hList[hIndex]); \
    hIndex++

这里hCounthList都是调用_read_images该方法时传过来的参数,hi是名称为header_info结构体,通过定义我们大约可以猜测出来,这是在遍历类的头文件,而hi中就是类的头文件的信息。然后我们通过_getObjc2CategoryList方法获取到hicategory_t列表(里面包含了当前类的所有category_t)和长度。

category_t **catlist = 
            _getObjc2CategoryList(hi, &count);

拿到列表和长度后下面又是通过for循环来进行遍历,获取到每一个category_t,并且根据category_tcls指针来获取到对应的类:

category_t *cat = catlist[i];
Class cls = remapClass(cat->cls);

获取到category_t和对应的类后,通过addUnattachedCategoryForClass方法将Category和类先关联起来(这里只是关联起来,并没有做其他的操作),下面通过remethodizeClass方法来整理相应的类:

static void remethodizeClass(Class cls)
{
    category_list *cats;
    bool isMeta;

    runtimeLock.assertLocked();

    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)" : "");
        }
        
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}

remethodizeClass方法中,我们看见通过unattachedCategoriesForClass方法将刚才关联的类的Category获取到,获取到category_list类型的列表后(category_list类型的列表包含了当前类所有的Category),执行了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.
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);
}

执行attachCategories首先执行下列代码重新分配分类的内存:

    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));

分配完内存地址后就开始遍历所有的分类,将每一个分类的方法、属性和协议添加到对应的mlistsproplistsprotolists中。添加完成后通过data()方法来拿到类对象的class_rw_t结构体类型的rw,之后通过调用rw中的方法列表、属性列表和协议列表的attachLists函数,将所有分类的方法、属性和协议列表数组添加进去。
下面我们来看一下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;
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            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]));
        }
    }
addLists:调用方法时传过来的,也就是要添加的分类的方法或属性列表
array()->lists:类中原有的方法或属性列表

下面我们看一下方法中的两个函数:memmovememcpy
这两函数都是C语言中的函数库,作用都是拷贝一定长度的内存内容,其长度由第三参数决定,他们两个唯一的区别是:当内存发生局部重叠时,memmove能够保证拷贝结果的正确行,而memcpy不能保证拷贝结果是正确的(在这里这两个方法就不多介绍了有兴趣的同学可以参考一下这里,关于memmove 和 memcpy的区别)。
  通过上面两个方法我们就把Category里面的方法放到了类中原方法的前面,所以当我们调用的时候会优先调用Category中的方法。(注:有些人说Category里面的方法把类中原有的方法覆盖了,其实这是错误的。Category中的方法并没有覆盖类中原有的方法,只是Category中的方法在类中原有的方法前面,当Runtime通过方法名查找的时候找到第一个方法就去执行了它的实现,并没有继续往下查找,关于方法的执行可以参考这里)。我们可以通过以下代码来调用类中原来的方法:

///Cat为自己创建的类,在类中声明一个sleep方法,创建一个cat的Category,声明并实现sleep方法
Class currentClass = [Cat class];
    Cat *cat = [[Cat alloc] init];
    [cat sleep];
    if (currentClass) {
        unsigned int methodCount;
        Method *methodList = class_copyMethodList(currentClass, &methodCount);
        IMP lastImp = NULL;
        SEL lastSel = NULL;
        for (NSInteger i = 0; i < methodCount; i++) {
            Method method = methodList[i];
            NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(method))
                                                      encoding:NSUTF8StringEncoding];
            if ([@"sleep" isEqualToString:methodName]) {
                lastImp = method_getImplementation(method);
                lastSel = method_getName(method);
            }
        }
        typedef void (*fn)(id,SEL);
        
        if (lastImp != NULL) {
            fn f = (fn)lastImp;
            f(cat,lastSel);
        }
        free(methodList);
    }

  以上就是Category的实现原理。通过这些我们也就了解了一些,Category中的属性、方法、协议是在运行时被添加到了类的属性列表、方法列表、协议列表中,既然它里面的方法是被添加到了类的方法列表中,那么它里面方法的调用和类中方法的调用是一样的。

Category的使用

  • 添加方法
  • 声明私有方法
  • 分解体积庞大的类文件
    以上是Apple推荐的使用方法,当然还有一些人开发出了其他的用法,比如:模拟多继承、把framework私有方法公开,感兴趣的朋友可以去了解一下。

Category和Extension的区别

  • Category中原则上只能增加方法,不能增加属性(通过Runtime也可以实现);Extension既可以增加方法,还可以增加实例变量(该实例变量和方法默认是私有的,只能在本类中调用)
  • Category中的方法是在运行时决议的,没有实现也可以运行,而Extension中的方法是在编译器检查的,没有实现会报错
  • Category可以给任意类添加方法,而Extension的添加必须有这个类的源码,对于一些系统类,如NSString类是无法添加Extension的,但是可以添加Category。

结束

  以上就是有关Category的原理和使用,Category还是基于在Runtime上实现的,如果没有Runtime的支持Category就不能够实现。Category在我们开发中的使用还是很多的,大家可以通过源码去学习研究。
  文章若有不足之处还请不吝赐教,大家互相学习。如果您觉得我的文章有用,点一下喜欢就可以了哦。

参考文章

iOS底层原理总结 - Category的本质
iOS-分类(Category)

相关文章

网友评论

    本文标题:iOS Category的使用及原理

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