OC category, protocol, and oc category agreement
Category: Add new methods for existing classes
1. When a new method of the class needs to be added, but the class cannot be inherited
Notes for category usage:
1. instance variables cannot be added to a category, but attributes can be declared for a category, but the set get method must be implemented. The added instance methods cannot be used in these two implementation methods.
2. The method added in the category cannot be the same as the method in the original class, otherwise it will overwrite
3. Multiple categories can be added to a class, but the category name and method name cannot be repeated.
4. Methods in a category can be part of the original class, which is at the same level as the original class method and can be inherited by the quilt class.
Class creation and use:
File: the name of the category.
File Type: Yes. This is Category.
Class: indicates the Class to be added.
// Name of the added category
// Add method-(void) hi in the. h file; implement it in the. m file
In the main file, remember to import the category file
In this way, you can create and implement a category.
Hide category (Extension): Private method of category
In the. m file of the category to be added# Import "class name"
// This part is extended (anonymous category)
@ Interface Student ()
// We recommend that you put the instance variables in the extension.
{
NSInteger _ age;
} // Resolve the conflict between private methods that need to be added but cannot be declared in the header file
@ Property (nonatomic, strong) NSString * name;
// Declare the private method here
-(Void) printHello;
@ End
This completes an anonymous category. It should be noted that the printHello method cannot be used in the main file, and printHello is a private method and cannot be used by other classes, can only be called by anonymous category
Protocol: it is a set of standards. Many methods are declared in this standard, but we are concerned about how these methods are implemented. The specific implementation is done by the class following this protocol.
The inheritance relationship in OC is a single inheritance, but sometimes we need to use multiple inheritance, then we can use the protocol.
File: protocol name
File Type: Type (select Protocol)
// Create a Student class,
Student. h file
Student. m
Implementation methods in the Protocol
Implemented in the main file
In this way, a simple protocol has been implemented.