将来跳槽用

iOS基础-类的了解

2023-03-18  本文已影响0人  萧修

本文目标:
1、理清objc_class和objc_object关系,知道里面存放ias指针
2、可以下载苹果源码
https://gitee.com/renrencai110/objc4-8669-source-code.git

NSObject、Class、objc_object、objc_class、id。

typedef这个是重新定义,简化称号

在源码Source文件夹下的NSObject查到

+ (Class)class {
    return self;
}

#if !OBJC_TYPES_DEFINED
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;

/// Represents an instance of a class.
struct objc_object {
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.
typedef struct objc_object *id;
#endif

//和NSObject是一个,在不同语言环境叫法不一样在C语言中叫objc_object

objc_class是一个代表对象类的结构体,所以NSObject类中包含的是一个objc_class结构体类型的isa,指向该对象对应的类

struct objc_class : objc_object {
  objc_class(const objc_class&) = delete;
  objc_class(objc_class&&) = delete;
  void operator=(const objc_class&) = delete;
  void operator=(objc_class&&) = delete;
    // Class ISA;
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags

  }

objc_object是一个代表对象实例的结构体,objc_object中只包含一个isa_t结构体类型的isa,所以objc_class中也会包含一个isa_t结构体类型的isa。**这个isa_t结构体包含了当前对象指向的类的信息。

struct objc_object {
private:
    char isa_storage[sizeof(isa_t)];

    isa_t &isa() { return *reinterpret_cast<isa_t *>(isa_storage); }
    const isa_t &isa() const { return *reinterpret_cast<const isa_t *>(isa_storage); }

public:

    // ISA() assumes this is NOT a tagged pointer object
    Class ISA(bool authenticated = false);

    // rawISA() assumes this is NOT a tagged pointer object or a non pointer ISA
    Class rawISA();

    // getIsa() allows this to be a tagged pointer object
    Class getIsa();
    
    uintptr_t isaBits() const;

从objc_class和objc_object的关系,和数据类型看,可以得出类的本质是一个结构体,里面有Class、cache_t、class_data_bits_t

其中cache_t、class_data_bits_t里面还是结构体

上一篇 下一篇

猜你喜欢

热点阅读