【MJ-iOS底层原理总结】分类方法为什么会先执行?源码分析

93 阅读3分钟
1. Category的使用
  1. 假设当前有Person类
    // Person.h
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    - (void)eat;
    
    - (void)run;
    
    @end
    
    // Person.m
    #import "Person.h"
    
    @implementation Person
    
    -(void)eat{
        NSLog(@"eat");
    }
    
    -(void)run{
        NSLog(@"run");
    }
    
    @end
    
  2. Person有分类Eat和Run
    • Person+Eat
    // Person+Eat.h
    #import "Person.h"
    
    @interface Person (Eat)
    
    - (void)eat;
    
    @end
    
    // Person+Eat.m
    #import "Person+Eat.h"
    
    @implementation Person (Eat)
    
    - (void)eat{
        NSLog(@"Person + Eat");
    }
    
    @end
    
    • Person+Run
    // Person+Eat.h
    #import "Person.h"
    
    @interface Person (Eat)
    
    - (void)eat;
    
    @end
    
    // Person+Eat.m
    #import "Person+Eat.h"
    
    @implementation Person (Eat)
    
    - (void)eat{
        NSLog(@"Person + Eat");
    }
    
    @end
    
  3. 此时执行代码
    Person *p = [Person new];
    [p run];
    [p eat];
    
    得到的结果为分类中的输出结果: image.png
2. Category的底层结构
  1. 结论:通过runtime动态将分类的方法合并到类对象、元类对象中
  2. 开始进行验证,首先看一下Person+Eat.m编译后源码的样子,核心源码如下:
    • 分类的底层通用结构,发现其中有类名实例方法列表类方法列表协议列表属性列表
    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;
    };
    
    • 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,
        0,
    };
    
    • 继续追溯,_CATEGORY_INSTANCE_METHODS_Person_$_Eat
    static struct /*_method_list_t*/ {
        unsigned int entsize;  // sizeof(struct _objc_method)
        unsigned int method_count;
        struct _objc_method method_list[1];
    } _OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_Eat __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_objc_method),
        1,
        {{(struct objc_selector *)"eat", "v16@0:8", (void *)_I_Person_Eat_eat}}
    };
    
    • 发现其中有名为eat的方法。结论:所以我们验证了,编译完成时,分类中的方法是存放在_category_t的底层结构体中的,暂时并没有合并到Person类中,所以下一步我们需要去看Runtime源码进行验证。
3. 查看Category的Runtime源码
  1. 查看category_t结构体如下:

    struct category_t {
        const char *name;
        classref_t cls;
        WrappedPtr<method_list_t, PtrauthStrip> instanceMethods;
        WrappedPtr<method_list_t, PtrauthStrip> 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);
    
        protocol_list_t *protocolsForMeta(bool isMeta) {
            if (isMeta) return nullptr;
            else return protocols;
        }
    };
    
  2. 开始追溯,追溯入口:objc-os.mm,运行时的源码一般都是在这个类中的。

    • 找到初始化方法:
       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();
       _imp_implementationWithBlock_init();
       _dyld_objc_notify_register(&map_images, load_images, unmap_image);
       }
      
    • 继续查看:map_images
      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);
      }
      
    • 继续查看:map_images_nolock
      _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
      
    • 继续查看:_read_images,此处images并非图片的意思,而是镜像、模块的意思
      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);
              }
          }
      }
      
    • 继续查看:load_categories_nolock
      static void load_categories_nolock(header_info *hi) {
          ...
          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());
             }
         }
      }
      
    • 最终核心方法:attachCategories
      static void
      attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count, int flags){
           ...
           constexpr uint32_t ATTACH_BUFSIZ = 64;
           method_list_t   *mlists[ATTACH_BUFSIZ];
           uint32_t mcount = 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, __func__);
                       rwe->methods.attachLists(mlists, mcount);
                       mcount = 0;
                   }
                   mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
                   fromBundle |= entry.hi->isBundle();
               }
           }
      }
      
      • cls: 类对象
      • cats_list:分类列表
      • 以下操作为:将所有分类的对象方法,附加到类对象的方法列表中
      prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
      rwe->methods.attachLists(mlists, mcount)
      
    • 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;
                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();
            }
      }
      
    • 如下源码,表示分类中的方法列表,添加到了原本的方法之前。由此证明了,分类方法会先执行的原因。
      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];
      
  3. 最终,方法列表在内存中的样子为:

    image.png