iOS - 对象的本质

557 阅读1分钟

做开发这么多年 一直在调侃 万物皆对象 那到底什么是对象 对象的本质是什么?

结构体 位域 联合体
  • 结构体
    • 结构体中的所有变量都是共存的 不管用不用 都分配内存空间
  • 联合体
    • 联合体中是个变量互斥的 一个赋值 其他都不能使用 只会分配一个内存空间

对象的指针 isa
 + (id)alloc -> _objc_rootAlloc -> callAlloc -> _objc_rootAllocWithZone -> _class_createInstanceFromZone
!!!这步骤llvm会优化

_class_createInstanceFromZone这个函数里面 如下图 这一步是将我们开辟的内存地址用isa指针关联到我们的对象

image.png

  1. isa 因为isa指针8字节单纯存储类信息有点浪费空间 事实上 一些信息 如是否释放 引用计数 weak 关联对象 析构函数 等
    • nonPointterIsa (一般创建的都是非纯指针 纯指针是指 只存储类信息shiftcls)
  • isa_t 结构体 arm_64架构下
union isa_t { //union 联合体

    isa_t() { }

    isa_t(uintptr_t value) : bits(value) { }

    uintptr_t bits;

private:

    // Accessing the class requires custom ptrauth operations, so

    // force clients to go through setClass/getClass by making this

    // private.

    Class cls;

public:

#if defined(ISA_BITFIELD)

    struct {

        ISA_BITFIELD;  // defined in isa.h

    };

\


    bool isDeallocating() {

        return extra_rc == 0 && has_sidetable_rc == 0;

    }

    void setDeallocating() {

        extra_rc = 0;

        has_sidetable_rc = 0;

    }

#endif

    void setClass(Class cls, objc_object *obj);

    Class getClass(bool authenticated);

    Class getDecodedClass(bool authenticated);

};
define ISA_BITFIELD                                                      \

        uintptr_t nonpointer        : 1;      是否纯指针标志位                                 \

        uintptr_t has_assoc         : 1;        关联对象                               \

        uintptr_t has_cxx_dtor      : 1;        c++析构                               \

        uintptr_t shiftcls          : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \类的指针地址

        uintptr_t magic             : 6;                                       \

        uintptr_t weakly_referenced : 1;     弱引用                                  \

        uintptr_t unused            : 1;                                       \

        uintptr_t has_sidetable_rc  : 1;      散列表                                 \

        uintptr_t extra_rc          : 19      引用计数
        
  • 代码看下isa里面的具体信息 下图就是取出isa 4-48 位的shiftcls 也就是类信息(x_86=结构下的 4 - 48 位)
#   define ISA_BITFIELD                                                        \

      uintptr_t nonpointer        : 1;                                         \

      uintptr_t has_assoc         : 1;                                         \

      uintptr_t has_cxx_dtor      : 1;                                         \

      uintptr_t shiftcls          : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \

      uintptr_t magic             : 6;                                         \

      uintptr_t weakly_referenced : 1;                                         \

      uintptr_t unused            : 1;                                         \

      uintptr_t has_sidetable_rc  : 1;                                         \

      uintptr_t extra_rc          : 8

image.png

总结
  • 对象的本质就是将类的一些信息关联的结构体