In this article, we will study two issues:
I. Implementation principle of Category?
Ii. What is the difference between Category and Extension?
Brief introduction:
Category is a language feature added after Objective-C 2.0. Categories and categories actually refer to categories. The main purpose of a Category is to add methods to an existing class.
Categories in Objective-C are a concrete implementation of the decorator pattern. Its main purpose is to dynamically add methods to a class without changing the original class.
Knowledge review:
When oc runs, it calls the run, eat, and test methods inside objc_msgSend(person,@selector(eat)). As we know from previous blog, object methods are stored in class objects. Do the test and EAT classes themselves generate a derived class? Is that so? You might wonder, well, it’s not true, a class has only one class object, and we’re going to look at that.
We use terminal to classify Test and eat into the underlying c++ file, using: xcrun-sdk iphoneos clang -arch arm64-rewrite-objc GDPerson+ test.m
I’m only going to go to one file, and the other file will do the same thing, and you can try it, but the classification information will generate a structure called _category_T, and it will have name, CLS, Instance_methods (object methods), class_methods, protocols, and properties. There is only one Test method. If you write two methods and go to the c++ file, there will be two. You can try it yourself. As you can see, no new classes are produced at compile time!
Read the source code :(opensource.apple)
Here we go to take a look at the source code implementation, due to the source code steps more, can not be all listed, I put the source code to find the order of hair, and then list the final results and implementation
The last step in the picture above: Realloc, MemMove and memcpy is a comparison of the previous version, see my screenshot below, is the latest version
Then we look for the attachLists method concrete implementation
We can draw some conclusions from this,
Conclusion:
What is the loading process of a Category?
1. Load all Category data of a Category through the Runtime
2. Merge all the Category methods, attributes, and protocol data into a large array. The later compiled Category data will be at the front of the array
3. Insert the merged classification data (methods, attributes, protocols, etc.) into the original data of the class
Ii. Realization principle of Category?
1. The underlying structure after Category compilation is struct category_t, which stores classified object methods, class methods, attributes, and protocol information
2. When the program runs, the Runtime merges the category data into the class information (class object, metaclass object).
Iii. What is the difference between Category and Class Extension?
Class Extension data is stored in the Class information at compile time, while Category data is merged into the Class information at run time.