ios&&OC

Object-C Runtime:对象、类、元类以及方法

2019-08-16  本文已影响0人  kindom_0129

1. 在 objc/runtime.h 中,Class(类)被定义为指向objc_class 结构体的指针,objc_class 结构体的数据结构如下:

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

struct objc_class {
    Class _Nonnull isa;                                          // objc_class 结构体的实例指针

#if !__OBJC2__
    Class _Nullable super_class;                                 // 指向父类的指针
    const char * _Nonnull name;                                  // 类的名字
    long version;                                                // 类的版本信息,默认为 0
    long info;                                                   // 类的信息,供运行期使用的一些位标识
    long instance_size;                                          // 该类的实例变量大小;
    struct objc_ivar_list * _Nullable ivars;                     // 该类的实例变量列表
    struct objc_method_list * _Nullable * _Nullable methodLists; // 方法定义的列表
    struct objc_cache * _Nonnull cache;                          // 方法缓存
    struct objc_protocol_list * _Nullable protocols;             // 遵守的协议列表
#endif

};

2.objc/objc.h 中关于 Object(对象) 的定义
Object(对象)被定义为objc_object 结构体,其数据结构如下:

/// Represents an instance of a class.
struct objc_object {
    Class _Nonnull isa;       // objc_object 结构体的实例指针
};

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

3. Meta Class(元类)
从上边我们看出,对象(objc_object 结构体) 的isa 指针指向的是对应的类对象(object_class 结构体)。那么类对象(object_class 结构体)的 isa 指针又指向什么呢?

4.实例对象(object)、class(类)、Meta Class(元类)之间的关系

图片来自网络

5.最后说下Method(方法)
object_class 结构体的methodLists(方法列表)中存放的元素就是Method(方法)。
在objc/runtime.h 中,表示Method(方法) 的 objc_method 结构体 的数据结构:

/// An opaque type that represents a method in a class definition.
/// 代表类定义中一个方法的不透明类型
typedef struct objc_method *Method;

struct objc_method {
    SEL _Nonnull method_name;                    // 方法名
    char * _Nullable method_types;               // 方法类型
    IMP _Nonnull method_imp;                     // 方法实现
};
/// An opaque type that represents a method selector.
typedef struct objc_selector *SEL;

SEL 是一个指向 objc_selector 结构体的指针,只是一个保存方法名的字符串。

SEL sel = @selector(viewDidLoad);
NSLog(@"%s", sel);              // 输出:viewDidLoad
SEL sel1 = @selector(testSEL);
NSLog(@"%s", sel1);             // 输出:testSEL
/// A pointer to the function of a method implementation. 
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ ); 
#else
typedef id _Nullable (*IMP)(id _Nonnull, SEL _Nonnull, ...); 
#endif

IMP 的实质是一个函数指针,所指向的就是方法的实现。IMP用来找到函数地址,然后执行函数。

上一篇 下一篇

猜你喜欢

热点阅读