美文网首页
探究Category本质

探究Category本质

作者: 我是C | 来源:发表于2018-08-17 13:55 被阅读213次

    细致的看了下Category的东西,记录一下。

    Category用途:
    1.进行类扩展
    2.hook一个方法
    3.重写已有类中的一个方法

    跟着代码走不会错。
    首先创建三个类分别是Person,Person+eat,Person+sleep。

    //1 Person
    @interface Person : NSObject
    - (void)run;
    @end
    
    //2 Person+eat
    @interface Person (eat)
    - (void)eat;
    @end
    
    //3 Person+sleep
    @interface Person (sleep)
    - (void)sleep;
    @end
    

    cpp 重写 Person+eat 代码
    xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Person+eat.m -o Person+eat-arm64.cpp
    可以看到Category类的结构:

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

    发现有一个 struct _category_t 类型的 _OBJC_$_CATEGORY_Person_$_eat

    static struct _category_t _OBJC_$_CATEGORY_Person_$_eat __attribute__ ((used, section ("__DATA,__objc_const"))) = 
    {
        "Person",
        0, // &OBJC_CLASS_$_Person,
        (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_eat,
        0,
        0,
        0,
    };
    

    由于我只写了一个对象方法,所以变量中只有 _method_list_t

    然后我们看看Category的源码:
    https://opensource.apple.com/tarballs/ 找到 objc4,下载源码。

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

    代码结构 和 cpp 重写的略有不同

    结构看接口大概就知道什么意思,类名,对象方法列表,类对象方法列表,协议列表等等。

    然后我们深入去看,类别如何将方法,属性合并到已有类中的。
    1.objc-os.mm 文件
    2.map_images方法
    3.map_images_nolock方法
    4._read_images方法
    5.remethodizeClass 重新组织方法

    static void remethodizeClass(Class cls)
    {
        category_list *cats;
        bool isMeta;
        runtimeLock.assertWriting();
        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);
        }
    }
    

    点击 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_t,method_t],[method_t,method_t]]
        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);
    }
    

    有详细的注释,主要注意的地方:
    while (i--) 说明是后面的category 方法列表 先放到mlists数组里,cats->list顺序与 compile soure 的编译顺序相关。说明最后的分类,优先放到方法前面。

    进入到 rw->methods.attachLists(mlists, mcount); 方法中,源码如下:

    void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;
    
        //addedCount 分类个数
        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            //realloc 重新创建 array(),大小是 类中原来的方法列表数量+categoory方法列表数量
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;
            //移动,将原来的方法列表移动到后面,移动了addedCount,相当于把分类方法列表的位置给空出来,其实index是
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            //将分类方法列表,拷贝到数组中,起始是0
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
            
        }
    }
    

    很关键的两个点:memmove,memcpy

    memmove : [3,4,2,1] - > 右移2位 - > [3,4,3,4]。
    可以完整的挪动3和4
    memcpy:[3,4,2,1] - > 右移2位 - > [3,3,3,1]。
    3移动到4,4位置变成3,4位置的3再移动到2位置,2位置的元素变成3,因此memcpy 会丢失原有的元素。

    综上总结一下:
    1.Category本质是个_category_t结构体
    2.Category通过runtime动态将分类的方法合并到类对象、元类对象中
    3.合并方法时,realloc 重新创建 array() (二维数组**method_lists),首先将原来的方法列表移动到后面,把Category的方法列表位置空出来,然后将Category_list的方法列表拷贝到array() 中。
    4.Category_list 的顺序,与 commplie source 顺序有关。
    5.对于同一个方法后加入的类别会覆盖先加入的类别中和类中的方法

    相关文章

      网友评论

          本文标题:探究Category本质

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