前言

上一节我们已经了解了objc_class结构体的内容了,也分析了isa和superclass的功能,我们在来看看objc_class结构体,来开启我们bits的探索之路。

  1. struct objc_class : objc_object {
  2. // Class ISA;
  3. // Class _Nonnull isa OBJC_ISA_AVAILABILITY;
  4. Class superclass;
  5. cache_t cache; // formerly cache pointer and vtable
  6. class_data_bits_t bits;
  7. }

找到bits的地址

首先我们可以通过p/x打印出对象的首地址,我们知道每个指针占8字节,那么isa和superclass都是指针各占8字节,那么我们只要知道cache占多少字节,通过地址平移就可以知道bits的首地址了。

探索cache的内存大小

通过源码我们可以看到cache是一个cache_t的结构体

我们先看一下cache_t的结构体源码

  1. struct cache_t {
  2. private:
  3. explicit_atomic<uintptr_t> _bucketsAndMaybeMask; // uintptr_t = long 占8字节
  4. union { // 共用体,共用体的内存大等于成员中最大的成员占内存,所以占8字节
  5. struct {
  6. explicit_atomic<mask_t> _maybeMask; // mask_t = int32 占4字节
  7. #if __LP64__
  8. uint16_t _flags; // 占2字节
  9. #endif
  10. uint16_t _occupied; // 占2字节
  11. };
  12. explicit_atomic<preopt_cache_t *> _originalPreoptCache; // 指针占8字节
  13. };
  14. }

由此分析得出cache_t的内容带下等于8+8共占16字节
所以我们现在就可以通过内存平移来查看bits的内容了,bits前边我们共需要平移8+8+16=32个字节

bits构成

class_data_bits_t

首先通过objc_class结构体我们可以看到bits是class_data_bits_t的结构体,我们先看一下class_data_bits_t的结构体源码

  1. struct class_data_bits_t {
  2. friend objc_class;
  3. // Values are the FAST_ flags above.
  4. uintptr_t bits;
  5. private:
  6. bool getBit(uintptr_t bit) const
  7. {
  8. return bits & bit;
  9. }
  10. public:
  11. // 关键内容-属性列表、方法列表、协议列表、成员变量等信息都存在这个结构体中
  12. class_rw_t* data() const {
  13. return (class_rw_t *)(bits & FAST_DATA_MASK);
  14. }
  15. };

我们可以看到class_data_bits_t结构体中的data()方法,该方法返回值为class_rw_t *的结构体指针,而我们类的属性列表、方法列表、协议列表、成员变量等信息全部都存放在这个结构体中,接下来我们继续探索class_rw_t这个结构体

class_rw_t

我们还是先看class_rw_t结构体的源码,我对源码进行了删减,留下主要我们要关注的部分

  • ro()方法会返回一个class_ro_t *的结构体指针,这个结构体中存储这成员变量信息;
  • methods()方法会返回method_array_t存储着方法列表信息;
  • properties()方法返回property_array_t存储着属性列表信息;
  • protocols()返回protocol_array_t存储着协议列表信息;

    1. struct class_rw_t {
    2. public:
    3. const class_ro_t *ro() const {
    4. auto v = get_ro_or_rwe();
    5. if (slowpath(v.is<class_rw_ext_t *>())) {
    6. return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->ro;
    7. }
    8. return v.get<const class_ro_t *>(&ro_or_rw_ext);
    9. }
    10. const method_array_t methods() const {
    11. auto v = get_ro_or_rwe();
    12. if (v.is<class_rw_ext_t *>()) {
    13. return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->methods;
    14. } else {
    15. return method_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseMethods()};
    16. }
    17. }
    18. const property_array_t properties() const {
    19. auto v = get_ro_or_rwe();
    20. if (v.is<class_rw_ext_t *>()) {
    21. return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->properties;
    22. } else {
    23. return property_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseProperties};
    24. }
    25. }
    26. const protocol_array_t protocols() const {
    27. auto v = get_ro_or_rwe();
    28. if (v.is<class_rw_ext_t *>()) {
    29. return v.get<class_rw_ext_t *>(&ro_or_rw_ext)->protocols;
    30. } else {
    31. return protocol_array_t{v.get<const class_ro_t *>(&ro_or_rw_ext)->baseProtocols};
    32. }
    33. }
    34. };

    list_array_tt

    穿插说明一下list_array_tt其实是一个结构体数组,内部声明了arrary_t结构体,arrary_t中的Ptr就是一个数组,所以我们返回的method_array_t、property_array_t、protocol_array_t都是数组,我们可以直接通过索引的方式获取数组的元素来查看存储的具体内容

    1. template <typename Element, typename List, template<typename> class Ptr>
    2. class list_array_tt {
    3. struct array_t {
    4. uint32_t count;
    5. Ptr<List> lists[0];
    6. static size_t byteSize(uint32_t count) {
    7. return sizeof(array_t) + count*sizeof(lists[0]);
    8. }
    9. size_t byteSize() {
    10. return byteSize(count);
    11. }
    12. };
    13. }

    method_array_t

    我们来看源码method_t就是方法的类型 ```objectivec class method_array_t : public list_array_tt { typedef list_array_tt Super;

    public: method_array_t() : Super() { } method_array_t(method_list_t *l) : Super(l) { }

    const method_list_t_authed_ptr *beginCategoryMethodLists() const {

    1. return beginLists();

    }

    const method_list_t_authed_ptr *endCategoryMethodLists(Class cls) const; };

  1. <a name="ewWKu"></a>
  2. #### method_t
  3. method_t中通过big结构体来存储方法选择器、参数类型、以及IMP地址
  4. ```objectivec
  5. struct method_t {
  6. static const uint32_t smallMethodListFlag = 0x80000000;
  7. method_t(const method_t &other) = delete;
  8. // The representation of a "big" method. This is the traditional
  9. // representation of three pointers storing the selector, types
  10. // and implementation.
  11. struct big {
  12. SEL name;
  13. const char *types;
  14. MethodListIMP imp;
  15. };
  16. }

property_array_t

我们来看源码property_t就是方法的类型

  1. class property_array_t :
  2. public list_array_tt<property_t, property_list_t, RawPtr>
  3. {
  4. typedef list_array_tt<property_t, property_list_t, RawPtr> Super;
  5. public:
  6. property_array_t() : Super() { }
  7. property_array_t(property_list_t *l) : Super(l) { }
  8. };

property_t

property_t结构体中只有name名称和attributes两个变量

  1. struct property_t {
  2. const char *name;
  3. const char *attributes;
  4. };

class_ro_t

class_ro_t中ivars存储这属性信息,类型时ivar_list_t *结构体指针

  1. struct class_ro_t {
  2. uint32_t flags;
  3. uint32_t instanceStart;
  4. uint32_t instanceSize;
  5. #ifdef __LP64__
  6. uint32_t reserved;
  7. #endif
  8. union {
  9. const uint8_t * ivarLayout;
  10. Class nonMetaclass;
  11. };
  12. explicit_atomic<const char *> name;
  13. // With ptrauth, this is signed if it points to a small list, but
  14. // may be unsigned if it points to a big list.
  15. void *baseMethodList;
  16. protocol_list_t * baseProtocols;
  17. const ivar_list_t * ivars;
  18. const uint8_t * weakIvarLayout;
  19. property_list_t *baseProperties;
  20. }

窥探bits

知识点补充

  1. 结构体类型调用方法可以直接用点语法进行调用
  2. 指针类型调用方法需要用“->”进行调用
  3. p *指针可以查看地址的内容

    Test文件结构

    ```objectivec

    import

NS_ASSUME_NONNULL_BEGIN

@protocol TestDelegate

  • (void) testProtocol;

@end

@interface Test : NSObject

@property (copy, nonatomic) NSString age; @property (copy, nonatomic) NSString name;

  • (void) test;
  • (void) classMethod;

@end

NS_ASSUME_NONNULL_END

  1. <a name="BmyZE"></a>
  2. ### 窥探步骤
  3. 1. 首先通过p/x查看对象的首地址
  4. 1. 地址平移32位得到bits的地址
  5. 1. 打印bits地址内容,并进行强制转换为class_data_bits_t *结构体指针
  6. 1. 调用data()查看class_rw_t *结构体指针
  7. 1. 调用methods查看方法列表
  8. 1. 调用properties查看属性列表
  9. 1. 调用ro()方法查看class_ro_t *结构体指针
  10. 1. 调用ivars查看成员变量信息
  11. <a name="KXCIp"></a>
  12. #### 先找到bits
  13. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632300600913-8fc878b1-a06a-4f79-9958-c424461d69d1.png#clientId=ua8dfec53-9c0c-4&from=paste&height=189&id=u7cdb19e0&margin=%5Bobject%20Object%5D&name=image.png&originHeight=354&originWidth=1498&originalType=binary&ratio=1&size=294942&status=done&style=none&taskId=u6ab6e1d7-0226-415b-aead-c7533722db9&width=800)
  14. <a name="nMId6"></a>
  15. #### 通过data()方法获取并查看class_rw_t
  16. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632300723077-70a878c5-cf8b-40c2-b65b-0e03136c5b6e.png#clientId=ua8dfec53-9c0c-4&from=paste&height=331&id=u368ca835&margin=%5Bobject%20Object%5D&name=image.png&originHeight=484&originWidth=1170&originalType=binary&ratio=1&size=311297&status=done&style=none&taskId=uf6ab38c2-2158-4f3b-91c8-73507ca5150&width=800)
  17. <a name="iInT1"></a>
  18. #### 调用method()查看方法列表
  19. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632301178566-1a6f8d2b-e769-4a82-8e8e-647195adb59c.png#clientId=ua8dfec53-9c0c-4&from=paste&height=546&id=u30066cf4&margin=%5Bobject%20Object%5D&name=image.png&originHeight=1446&originWidth=2120&originalType=binary&ratio=1&size=1551946&status=done&style=none&taskId=u4a689429-b6dd-4056-a287-e8722b1c0d7&width=800)
  20. <a name="Ngbyi"></a>
  21. #### 调用properties()查看属性列表
  22. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632361637968-1449d0e4-9b70-4c03-b2df-667a7f26b0f1.png#clientId=ua8dfec53-9c0c-4&from=paste&height=298&id=u202e930a&margin=%5Bobject%20Object%5D&name=image.png&originHeight=584&originWidth=1568&originalType=binary&ratio=1&size=428815&status=done&style=none&taskId=u7183e8b3-1209-48f4-a202-a2fbcb5fe73&width=800)
  23. <a name="wKIjB"></a>
  24. #### 调用ro()获取class_ro_t和ivars
  25. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632362022308-0c08a505-7a8e-4202-8575-a7e26f9bbfcb.png#clientId=ua8dfec53-9c0c-4&from=paste&height=455&id=ub300ca01&margin=%5Bobject%20Object%5D&name=image.png&originHeight=1088&originWidth=1912&originalType=binary&ratio=1&size=827539&status=done&style=none&taskId=u95ca1e38-c1ad-4152-aff6-2199e3d78d8&width=800)
  26. <a name="BfD8Q"></a>
  27. # 类方法呢?
  28. 上边我们通过class_rw_t获取方法列表,但是这个方法列表中只有实例方法信息,我们并没有看到类的方法,那么类方法在哪里存放呢?先给大家一个结论,实例方法是存放在类对象的方法列表中的,但是类方法是存放在类的原类对象的方法列表中。<br />下面我们来通过代码来证实一下:
  29. 1. 获取类方法的地址和内存排布
  30. 1. 通过类的isa指针获取到类的原类
  31. 1. 在获取原类的class_data_bits_t
  32. 1. 在通过data()方法获取class_rw_t
  33. 1. 在通过methods获取类方法列表
  34. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12834404/1632711920789-124816d7-260a-488e-922b-af2c35a6e433.png#clientId=u35865deb-4f5a-4&from=paste&height=344&id=uacc72cd0&margin=%5Bobject%20Object%5D&name=image.png&originHeight=1014&originWidth=2356&originalType=binary&ratio=1&size=962452&status=done&style=none&taskId=u19cf26fd-7698-4d82-945a-09da7ef4f54&width=800)
  35. <a name="do5f1"></a>
  36. # 面试题扩展
  37. <a name="lu9i0"></a>
  38. ## class_getInstanceMethod和class_getClassMethod
  39. class_getInstanceMethod:返回类的实例方法<br />class_getClassMethod:返回类的的类方法<br />我们来看一下下面代码分别打印什么:
  40. ```objectivec
  41. // 类中的方法声明
  42. // - (void) sayHello;
  43. // + (void) sayHappy;
  44. Method method1 = class_getInstanceMethod(pClass, @selector(sayHello)); // YES
  45. Method method2 = class_getInstanceMethod(metaClass, @selector(sayHello)); // NO
  46. Method method3 = class_getInstanceMethod(pClass, @selector(sayHappy)); // NO
  47. Method method4 = class_getInstanceMethod(metaClass, @selector(sayHappy)); // YES
  48. Method method1 = class_getClassMethod(pClass, @selector(sayHello)); // NO
  49. Method method2 = class_getClassMethod(metaClass, @selector(sayHello)); // NO
  50. Method method3 = class_getClassMethod(pClass, @selector(sayHappy)); // YES
  51. Method method4 = class_getClassMethod(metaClass, @selector(sayHappy)); // YES
  1. Method method4 = class_getInstanceMethod(metaClass, @selector(sayHappy));

此项能找到的原因是因为sayHappy是类方法,类方法存放在元类的方法列表中,那么元类的方法列表就是类方法,所以可以成功查询到sayHappy。

  1. Method method4 = class_getClassMethod(metaClass, @selector(sayHappy));

class_getClassMethod源码:

  1. /***********************************************************************
  2. * class_getClassMethod. Return the class method for the specified
  3. * class and selector.
  4. **********************************************************************/
  5. Method class_getClassMethod(Class cls, SEL sel)
  6. {
  7. if (!cls || !sel) return nil;
  8. return class_getInstanceMethod(cls->getMeta(), sel);
  9. }

getMeta()源码:

  1. Class getMeta() {
  2. if (isMetaClassMaybeUnrealized()) return (Class)this;
  3. else return this->ISA();
  4. }

通过class_getClassMethod源码我们可以看到,其内部获取类方法实质是哪传入的类获取了一次元类,在再元类的方法列表中进行查找,所以当传入类时,首先获取到元类,在查找方法,所以返回成功很容易理解。那么为什么传入元类的时候获取类方法也会返回正确呢,这个秘密其实在getMeta()方法中,getMeta()内部其实是有一层判断的,如果传入的类已经是元类了,那么就不会继续获取元类,而是直接返回,那么最终就还是获取当前元类的方法列表了,所以可以查到类方法。
总结:
class_getInstanceMethod:如果传入类对象则查找实例方法,如果传入元类对象则查找类方法;
class_getClassMethod:传入类对象或元类对象,都会查找当前类的类方法;

isKindOfClass和isMemberOfClass的区别

我们先分别看一下isKindOfClass和isMemberOfClass的源码:

isKindOfClass

  1. + (BOOL)isKindOfClass:(Class)cls {
  2. for (Class tcls = self->ISA(); tcls; tcls = tcls->getSuperclass()) {
  3. if (tcls == cls) return YES;
  4. }
  5. return NO;
  6. }
  7. - (BOOL)isKindOfClass:(Class)cls {
  8. for (Class tcls = [self class]; tcls; tcls = tcls->getSuperclass()) {
  9. if (tcls == cls) return YES;
  10. }
  11. return NO;
  12. }

源码说明

  • isKindOfClass类方法:

我们可以看到,tcls会先获取当前类的ISA,也就是获取元类,然后进行遍历比较,如果当前元类与传入的类一致,则返回YES,如果不一致则获取当前元类的父类,再次进行比较,直到比较到根元类NSObject时,再次获取superclass时会向前找一次,就会找到NSObject类,当再次获取Superclass时会返回null,返回NO。

  • isKindOfClass实例方法:

我们可以看到,tcls会先获取当前类的Class,也就是获取当前实例对象的类对象,然后进行遍历比较,如果当前类与传入的类一致,则返回YES,如果不一致则获取当前类的父类对象,再次进行比较,直到比较到根类NSObject时,再次获取Superclass时会返回null,返回NO。

总结:

  • isKindOfClass类方法比较的是元类,并且如果当前类是要比较的类的派生类的话,返回YES,否则返回NO;
  • isKindOfClass实例方法比较的是类,并且如果当前实例对象的类对象时要比较的类对象的派生类的话,返回YES,否则返回NO;

    isMenberOfClass

    ```objectivec
  • (BOOL)isMemberOfClass:(Class)cls { return self->ISA() == cls; }
  • (BOOL)isMemberOfClass:(Class)cls { return [self class] == cls; } ```

    源码说明

  • isMemberOfClass类方法

获取当前类的ISA,也就是元类,与传入的类对象进行比较,只比较一次,一致就返回YES,不一致则返回NO;

  • isMemberOfClass实例方法

获取当前实例对象的类对象,与传入的类对象进行比价,只比较一次,一致就返回YES,不一致则返回NO;