reference

Ke.qq.com/course/3145…

What’s a Category?

Categories are objective-C language features.

Categories and categories refer to categories.

The main purpose of a Category is to add methods to an existing class.

Implementation Principle of Category

After Category compilation, the underlying structure is struct category_t, which stores classified object methods, class methods, attributes, and protocol information.

And when you run your program, the Runtime merges the Category data into a class object, a metaclass object.

What is the difference between Category and Extension?

When the Extension is compiled, its data is already included in the class information.

Category data is merged into the class information at runtime.

Category associated object

By default, member variables cannot be added to a category because of the underlying structure of the category, but they can be done indirectly by associating objects.

For example:

Declare @property (nonatomic, copy) NSString *name; Implementation - (void)setName:(NSString *) Name {// the first parameter category object // the second parameter key // the third parameter value // the fourth parameter modifier objc_setAssociatedObject(self, @)"name", name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)name{
    
    return objc_getAssociatedObject(self, @"name"); } LSLPerson *person = [[LSLPerson alloc] init]; person.name = @"Lsl";
NSLog(@"% @",person.name);
Copy the code

The implementation principle of associated objects

supplement

1. Anonymous classes are merged at compile time. Anonymous classes are also called class extensions.

2. Different classes have the same methods, so the call sequence depends on the compile sequence.

3. If this article violates privacy or other things, please contact me, I will rectify or delete in the first time.