一、Runtime 可以做的是事情
1、实现多继承
2、交换两个方法的实现
3、关联对象
4、动态创建方法和类
5、将 Json 转化为 model
......
二、runtime 主要涉及的点
1、面向对象
struct objc_class {
Class isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
Class super_class OBJC2_UNAVAILABLE;
const charchar *name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE;
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
isa:指向元类的 objc_class 结构体指针,在 iOS 中 类也是对象,元类中存储着类对象的方法
super_class:指向该类的父类, 如果该类已经是最顶层的根类(如 NSObject 或 NSProxy),那么 super_class 就为 NULL.
name:类名
version:版本号,默认为0
info:!*!供运行期使用的一些位标识。如:CLS_CLASS (0x1L)表示该类为普通class; CLS_META(0x2L)表示该类为metaclass等(runtime.h中有详细列出)
instance_size:类实例变量的大小
ivars:该类成员变量链表,是objc_ivar_list结构体
struct objc_ivar_list {
int ivar_count OBJC2_UNAVAILABLE; // 成员变量个数
#ifdef __LP64__
int space OBJC2_UNAVAILABLE;
#endif
/* variable length structure */
struct objc_ivar ivar_list[1] OBJC2_UNAVAILABLE; // objc_ivar结构体存储类的单个成员变量信息。
} OBJC2_UNAVAILABLE;
objc_method_list:方法链表结构体 !*!根据info的信息确定是类还是实例,运行什么函数方法等
struct objc_method_list {
struct objc_method_list *obsolete OBJC2_UNAVAILABLE; //
int method_count OBJC2_UNAVAILABLE; // 方法个数
#ifdef __LP64__
int space OBJC2_UNAVAILABLE;
#endif
/* variable length structure */
struct objc_method method_list[1] OBJC2_UNAVAILABLE; // objc_method 存储类的当个方法信息
} OBJC2_UNAVAILABLE;
method: 对象的每个方法的结构体,SEL是方法选择器,是HASH后的值,可以通过这个值找到函数体的实现,IMP 是函数指针
struct objc_method {
SEL method_name OBJC2_UNAVAILABLE;
charchar *method_types OBJC2_UNAVAILABLE;
IMP method_imp OBJC2_UNAVAILABLE;
}
cache: 对象使用过的方法链表
struct objc_cache {
unsigned int mask /* total = mask + 1 */ OBJC2_UNAVAILABLE; // 分配用来缓存 bucket 的总数。
unsigned int occupied OBJC2_UNAVAILABLE; // 表明目前实际占用的缓存 bucket 的个数。
Method buckets[1] OBJC2_UNAVAILABLE; // 一个散列表,用来方法缓存,bucket_t 类型,包含 key 以及方法实现 IMP。
};
objc_protocol_list:协议链表
struct objc_protocol_list {
struct objc_protocol_list *next;
long count;
__unsafe_unretained Protocol *list[1];
};
2、消息分发
3、消息转发