在OC中给一个类添加分类后,程序在编译之后生成的底层结构是struct category_t
,里面存储着分类的name
(类名)、 instanceMethods
(对象方法)、classMethods
(类方法)、protocols
(属性)、instanceProperties
(协议信息)等。
在程序运行的时候,runtime会将Category的数据,合并到类信息中(类对象、元类对象中)
struct category_t {
const char *name;
classref_t cls;
struct method_list_t *instanceMethods;
struct method_list_t *classMethods;
struct protocol_list_t *protocols;
struct property_list_t *instanceProperties;
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
.
.
.
};
分类中的对象方法、类方法、属性、协议信息最后会被合并到结构体class_rw_t的methods
(方法列表)、properties
(属性列表)、protocols
(协议列表)
Category的加载处理过程
- 通过Runtime加载某个类的所有Category数据
- 把所有Category的方法、属性、协议数据,合并到一个大数组中,后面参与编译的Category数据,会在数组的前面
- 将合并后的分类数据(方法、属性、协议),插入到类原来数据的前面
所以在多个分类或原来类中都存在的方法会根据插入方法列表中的顺序调用。一般都是后编译的会插入在方法列表的最前面
通过xcode控制编译的顺序
- 选中当前的Targets -> Build Phases -> Compile Source
- 在先后次序添加编译的代码文件
OC类的类信息载入顺序
先在内存中载入原本类信息,在载入分类的类信息