第一部分:有关分类的本质、原理
Q:分类的对象方法,类方法都存在哪里?
一个类的所有分类的 对象方法放在类对象中,所有分类的类方法存放在元类中
clang查看编译文件
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc NSObject+Test.m
编译文件NSObject+Test.cpp中有关分类内容
//声明结构体
struct _category_t {
const char *name; //类的名字(name)
struct _class_t *cls; //类(cls)
const struct _method_list_t *instance_methods;//category中所有给类添加的实例方法的列表(instanceMethods)
const struct _method_list_t *class_methods;//category中所有添加的类方法的列表(classMethods)
const struct _protocol_list_t *protocols; //category实现的所有协议的列表(protocols)
const struct _prop_list_t *properties; //category中添加的所有属性(instanceProperties)
};
//对结构体赋值
static struct _category_t _OBJC_$_CATEGORY_NSObject_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"NSObject",
0, // &OBJC_CLASS_$_NSObject,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_NSObject_$_Test,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_NSObject_$_Test,
(const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_NSObject_$_Test,
0,
};
Runtime中Category源码解读顺序
objc-os.mm
- _objc_init
- map_images
- map_images_nolock
objc-runtime-new.mm
- _read_images
- remethodizeClass
- attachCategories
- attachLists
- realloc、memmove、 memcpy
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;
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
objc-runtime-new.mm
// cls 类
// cats 分类列表
static void
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
if (!cats) return;
if (PrintReplacedMethods) printReplacements(cls, cats);
bool isMeta = cls->isMetaClass();
// fixme rearrange to remove these intermediate allocations
/*方法数组
[
[method_t,method_t]
[method_t,method_t]
]
*/
method_list_t **mlists = (method_list_t **)
malloc(cats->count * sizeof(*mlists));
//属性数组
property_list_t **proplists = (property_list_t **)
malloc(cats->count * sizeof(*proplists));
//协议数组
protocol_list_t **protolists = (protocol_list_t **)
malloc(cats->count * sizeof(*protolists));
// Count backwards through cats to get newest categories first
int mcount = 0;
int propcount = 0;
int protocount = 0;
int i = cats->count;
bool fromBundle = NO;
while (i--) {
//取出分类
auto& entry = cats->list[i];
//取出分类对象方法
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
mlists[mcount++] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
proplists[propcount++] = proplist;
}
protocol_list_t *protolist = entry.c