What is the underlying structure of a Category?
Balance:
Let’s start by creating a class
@interface CTTestClass : NSObject
@end
Copy the code
Then create a category and add: – methods, + methods, protocols, attributes
@interface CTTestClass (Test)<NSCopying,NSCoding>
-(void)test1;
@property (assign, nonatomic) int weight;
@property (assign, nonatomic) double height;
@end
Copy the code
@implementation CTTestClass (Test)
-(void)test1{
}
+(void)test2{
}
@end
Copy the code
Then, the feature begins.
We open the command line, go to the code folder, and type:
Cxcrun-sdk iphoneOS clang -arch – rerewrite -objc CTTestClass+ test. m; ctestClass + test. m; ctestClass + test. m; ctestClass + test. m; ctestClass + test. m; ctestClass + test. m;
The compiler looks like this:
! [img1] (/ Users/CCT Mobile Documents/com/Library/apple CloudDocs/markDown/imgs/Category, rounding bottom – 1 / img1. PNG)
Don’t panic, let’s search: _category_t
You see a structure like this:
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;
};
Copy the code
Yeah, that’s it, the real structure of a Category, is this thing.
Think by name,
Name is a class name, CLS is a class, instance_methods is an object method, class_methods is a class method, protocols is a protocol, and properties is a property. So let’s verify that there are these things in the classification we just created. Let’s look for the underlying implementation.
Continue searching: _category_t
You can see this thing right here
static struct _category_t _OBJC_The $_CATEGORY_CTTestClass_The $_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,
};
Copy the code
This is a _category_T structure named _OBJC_$_CATEGORY_CTTestClass_$_Test
If we look at what it says,
Const char *name in _category_t;
The second item: 0, followed by a comment, which needs no explanation, is the CTTestClass we created
The third: (const struct _method_list_t *) &_objc_ $_CATEGORY_INSTANCE_METHODS_CTTestClass_$_Test _INSTANCE_METHODS_, const struct _method_list_t *instance_methods in _category_t
Const struct _PROTOCOL_LIST_t *protocols from _category_t
Struct _protocol_LIST_t *properties const struct _protocol_T *properties