1. Basic concepts of category
Encapsulation is an object-oriented feature, and OC is no exception. However, sometimes we encounter a situation where we encapsulate a class and don't want to change it any more, however, we need to add a method to the class. At this time, we don't have to modify it in that class or define another subclass. We only need to add a category.
(1) A method defined in a category will become part of the original class, which is no different from calling other methods.
(2) by defining a category method for the parent class, its subclass also inherits these methods.
CATEGORY applications: (1) extension of existing classes (2) Replacement of subclasses (3) classification of methods in Classes
CATEGORY limitations:
You cannot add new instance variables to a category. The category does not have a location to accommodate instance variables. To add instance variables to a category, you can only define sub-classes.
If the method of the existing class is covered in the category, this will lead to the break of the Super message. Because the method in the category has a higher priority, generally do not overwrite the method of the existing class.
Category definition,
Naming rules for a class: Class Name (extension method name)
The category does not inherit the parent class. You only need a bracket to indicate the purpose of the class.
# Import <Foundation/Foundation. h> @ interface nsstring (mycompare)-(void) test; @ end
# Import "nsstring + mycompare. H" @ implementation nsstring (mycompare)-(void) test {}@ end