美文网首页
十三、分类的加载原理

十三、分类的加载原理

作者: Mjs | 来源:发表于2020-10-20 14:44 被阅读0次

    分类

    main中添加LGPerson分类

    
    @interface LGPerson (LGA)
    @property(nonatomic,copy)NSString *cate_name;
    @property(nonatomic,assign)int cate_age;
    +(void)cate_sayClassMethod;
    -(void)cate_MethodA;
    -(void)cate_MethodC;
    -(void)cate_MethodB;
    
    @end
    @implementation LGPerson (LGA)
    
    
    +(void)cate_sayClassMethod{
        
    }
    -(void)cate_MethodA{
        
    }
    -(void)cate_MethodC{
        
    }
    -(void)cate_MethodB{
        
    }
    
    

    通过clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk main.mmian编译成c++文件

    
    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;
    };
    extern "C" __declspec(dllimport) struct objc_cache _objc_empty_cache;
    #pragma warning(disable:4273)
    
    static struct /*_method_list_t*/ {
        unsigned int entsize;  // sizeof(struct _objc_method)
        unsigned int method_count;
        struct _objc_method method_list[3];
    } _OBJC_$_CATEGORY_INSTANCE_METHODS_LGPerson_$_LGA __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_objc_method),
        3,
        {{(struct objc_selector *)"cate_MethodA", "v16@0:8", (void *)_I_LGPerson_LGA_cate_MethodA},
        {(struct objc_selector *)"cate_MethodC", "v16@0:8", (void *)_I_LGPerson_LGA_cate_MethodC},
        {(struct objc_selector *)"cate_MethodB", "v16@0:8", (void *)_I_LGPerson_LGA_cate_MethodB}}
    };
    
    static struct /*_method_list_t*/ {
        unsigned int entsize;  // sizeof(struct _objc_method)
        unsigned int method_count;
        struct _objc_method method_list[1];
    } _OBJC_$_CATEGORY_CLASS_METHODS_LGPerson_$_LGA __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_objc_method),
        1,
        {{(struct objc_selector *)"cate_sayClassMethod", "v16@0:8", (void *)_C_LGPerson_LGA_cate_sayClassMethod}}
    };
    
    static struct /*_prop_list_t*/ {
        unsigned int entsize;  // sizeof(struct _prop_t)
        unsigned int count_of_properties;
        struct _prop_t prop_list[2];
    } _OBJC_$_PROP_LIST_LGPerson_$_LGA __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_prop_t),
        2,
        {{"cate_name","T@\"NSString\",C,N"},
        {"cate_age","Ti,N"}}
    };
    

    我们可以看到没有getter setter {{(struct objc_selector *)"cate_MethodA", "v16@0:8", (void *)_I_LGPerson_LGA_cate_MethodA}method_t一致

    
    struct method_t {
        SEL name;
        const char *types;
        MethodListIMP imp;
    
        struct SortBySELAddress :
            public std::binary_function<const method_t&,
                                        const method_t&, bool>
        {
            bool operator() (const method_t& lhs,
                             const method_t& rhs)
            { return lhs.name < rhs.name; }
        };
    };
    

    我们也可以看官方文档shift+command+0搜索Category可以看到

    typedef struct objc_category *Category;
    
    struct objc_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;
    }                                                            OBJC2_UNAVAILABLE;
    

    我们在上面的methodizeClass方法中看到处理分类的方法objc::unattachedCategories.attachToClass

    
        void attachToClass(Class cls, Class previously, int flags)
        {
            runtimeLock.assertLocked();
            ASSERT((flags & ATTACH_CLASS) ||
                   (flags & ATTACH_METACLASS) ||
                   (flags & ATTACH_CLASS_AND_METACLASS));
    
            auto &map = get();
            auto it = map.find(previously);//分类一个一个查找处理
    
    
            if (it != map.end()) {
                category_list &list = it->second;
                if (flags & ATTACH_CLASS_AND_METACLASS) {
                    int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
                    attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
                    attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
                } else {
                    attachCategories(cls, list.array(), list.count(), flags);
                }
                map.erase(it);
            }
        }
    
    //将方法列表、属性和协议从类别附加到类中。
    //假设所有cats中的类别都已加载并按加载顺序排序,
    //先有最古老的类别。
    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();//rwe 初始化 本类被添加了
    
        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);
                    rwe->methods.attachLists(mlists, mcount);
                    mcount = 0;
                }
                mlists[ATTACH_BUFSIZ - ++mcount] = mlist;//倒序插入
                fromBundle |= entry.hi->isBundle();
            }
      ...
    
        }
    
        if (mcount > 0) {
            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);
    }
    
    
        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;//将list向后移,为新添加腾出位子
                memcpy(array()->lists, addedLists, 
                       addedCount * sizeof(array()->lists[0]));//新添加的插入前面,所以同名的会先调用分类方法
            }
        }
    

    这个时候我们可以全局搜索和通过lldb打印bt知道attachCategories流程

    attachCategories流程.png
    我们这里有两个分类
    
    @interface LGPerson (LGA)
    
    
    - (void)cateA_1;
    - (void)cateA_2;
    - (void)cateA_3;
    
    @end
    
    @implementation LGPerson (LGA)
    
    + (void)load{
        
    }
    
    - (void)kc_instanceMethod1{
        NSLog(@"%s",__func__);
    }
    
    
    - (void)cateA_2{
        NSLog(@"%s",__func__);
    }
    - (void)cateA_1{
        NSLog(@"%s",__func__);
    }
    - (void)cateA_3{
        NSLog(@"%s",__func__);
    }
    @end
    
    @interface LGPerson (LGB)
    - (void)cateB_1;
    - (void)cateB_2;
    - (void)cateB_3;
    @end
    
    @implementation LGPerson (LGB)
    
    + (void)load{
    
    }
    
    - (void)kc_instanceMethod1{
        NSLog(@"%s",__func__);
    }
    
    - (void)cateB_2{
        NSLog(@"%s",__func__);
    }
    - (void)cateB_1{
        NSLog(@"%s",__func__);
    }
    - (void)cateB_3{
        NSLog(@"%s",__func__);
    }
    

    我们在两个分类中都实现了load方法,所以我们一开始就加载了分类,现在我们调试下不实现load,一个分类加载load,会使其他分类提前加载

     1: 主类 load  分类 load      全部 - load_image 加载到数据
     2:  懒加载类 + ⾮懒加载分类 : 迫使类成为⾮懒加载类样式来提前加载数据
     3: 懒加载类 + 懒加载分类 : 消息第⼀次调⽤ (加载数据)
     4: ⾮懒加载类 + 懒加载分类 : read_image 就加载数据
    
    1,2属于运行期处理的;3,4属于编译期处理的
    

    相关文章

      网友评论

          本文标题:十三、分类的加载原理

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