1. Category (categories are also called categories. Add methods for classes without source code (System Classes and others' classes)
1) Role
Extends others' classes and can be used as an alternative to subclasses.
Put the code of the same class into multiple files.
2) Form
File Name:. h file (target class + category name. h). M file (target class + category name. m)
3) Note
You can add multiple categories for the same category, but the category name and method cannot be repeated.
Do not arbitrarily override methods in the original Class
The added class is the same as the method in the original class and inherits the quilt class.
Demo:
Add a category to a string
Nsstring + sayhi. h
@ Interface nsstring (sayhi)
-(Void) sayhi; // Method for adding strings
@ End
Nsstring + sayhi. m
@ Implementation nsstring (sayhi)
-(Void) sayhi
{
Nslog (@ "I am a special string % @, I have the sayhi method", self );
}
@ End
2. Extension (extension is a special category)
1) Role
Add a private method to your class
2) Form
This is in the. M file
@ Interface Class Name (extension name, which can be blank)
-(Return type) method;
@ End
@ Implementation Class Name
-(Return type) Method
{
}
@ End
3) Note
You do not need to create a new file and declare and implement it directly in the. M file of the original class.
In private mode, only. m is accessed through [self method] and cannot be accessed externally through [object method.
Demo:
Person. h
@ Interface person: nsobject
-(Void) sayhi;
@ End
Person. m
@ Interface person (Extension) // extend
-(Void) test; // Declaration
@ End
@ Implementation person
-(Void) sayhi
{
[Self test];
}
-(Void) test // implementation
{
Nslog (@"...");
}
@ End
3. Protocol (the Protocol is a list of methods declared by @ protocol. Only methods are declared, not specific) instance description proxy
1) Role
Remove the method definition to form a separate file.
2) Form
@ Protocol name <other protocols>
@ Required
-(Return type) method;
@ Optional
-(Return type) method;
@ End
Note: the default method is @ required, which must be implemented. If not, @ optional is used.
3) proxy mode (instance description proxy)
(The proxy mode is used by others to implement a function)
Accept proxy (. h file)
@ Interface Class Name: parent class name <protocol name 1, protocol name 2, protocol name 3> (multiple protocols are separated by commas)
@ End
Validation protocol (in the. M file)
@ Implementation Class Name
Methods declared in the Protocol
{
}
@ End
(Proxy = who accepts and confirms the Agreement)
4) Note
The Protocol declares methods that can be implemented by any class.
The Protocol defines an interface that can be implemented by other objects.