Category底层详解

522 阅读1分钟

Category底层结构是什么样的?

拿捏:

我们先来创建一个类

@interface CTTestClass : NSObject
@end

然后建立一个分类,在里面添加:-方法、+方法、协议、属性

@interface CTTestClass (Test)<NSCopying,NSCoding>

-(void)test1;

@property (assign, nonatomic) int weight;

@property (assign, nonatomic) double height;

@end
@implementation CTTestClass (Test)

-(void)test1{
    
}

+(void)test2{
    
}

@end

然后,正片开始。

我们打开命令行,进入到代码所在的文件夹,输入:

xcrun -sdk iphoneos clang -arch -rewrite-objc CTTestClass+Test.m 运行,将CTTestClass+Test.m编译为c++文件,我们通过查看编译后的代码,来了解其底层实现。

编译后是这样的:

![img1](/Users/cct/Library/Mobile Documents/comappleCloudDocs/markDown/imgs/Category底层详解-1/img1.png)

不要慌,我们来搜索:_category_t

会看到这么个结构体:

struct _category_t {
	const char *name;
	struct _class_t *cls;
	const struct _method_list_t *instance_methods;
	const struct _method_list_t *class_methods;
	const struct _protocol_list_t *protocols;
	const struct _prop_list_t *properties;
};

没错,就是它,Category真正的结构,是这么个东西。

见名思其意,

name就是分类名称、cls就是类、instance_methods是对象方法、class_methods是类方法、protocols是协议、properties是属性。那么我们来验证一下,刚我们创建的分类里面就有这些东西,来找找底层实现,拿捏:

继续搜索:_category_t

可以看到这个东西

static struct _category_t _OBJC_$_CATEGORY_CTTestClass_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
	"CTTestClass",
	0, // &OBJC_CLASS_$_CTTestClass,
	(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_CTTestClass_$_Test,
	(const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_CTTestClass_$_Test,
	(const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_CTTestClass_$_Test,
	(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_CTTestClass_$_Test,
};

这个一个 _category_t 类型的结构体,名字为 _OBJC_$_CATEGORY_CTTestClass_$_Test

我们看它的内容,

第一项:"CTTestClass",对应了_category_t里面的 const char *name

第二项:0,后面还打了个注释,不用多解释了吧,就是表示我们创建的CTTestClass

第三项:(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_CTTestClass_$_Test,这个挺长的,不过我们看它中间,写了 _INSTANCE_METHODS_,那用鼻子想也知道这就是对象方法,对应了_category_t里面的const struct _method_list_t *instance_methods

第五项:同上,对应了_category_t里面的 const struct _protocol_list_t *protocols

第六项:同上,对应了_category_t里面的 const struct _protocol_list_t *properties