Agreement:
- A protocol is not a class: it can only declare a method and cannot have any instance variables, it has two types: formal and informal, and the Protocol only declares files, no implementation files. Formal agreements are a collection of methods that follow a formal agreement in a class that must implement all the methods in the Protocol, and there is no limit to the number of protocols a class can follow. The informal protocol is also a collection of methods, but following the class in the informal protocol, you can choose the method of implementing the protocol according to your own needs, that is, the method in the informal protocol can not be implemented.
- Declare the general format of an agreement:
@protocol Protocolname<protocol,... >
Requiredmethoddeclarations//default is modified by @required
@optional
Optionalmethoddeclarations
@required
Requiredmethoddeclarations
@end
- The method that is modified by @optional can be chosen, and the method that is @required modified is necessary to be realized.
- The protocol usually does not have a specific association with any class, just provides a public interface for all classes.
- The protocol definition does not have a corresponding implementation part, the method in the protocol is implemented in the class that follows the protocol, if the class follows multiple protocols, the protocols are separated, and the methods in the implemented protocols can be inherited. (When a class follows certain protocols, it is equivalent to having the methods in those protocols)
- If you let the class follow the Nscopying protocol, declare the file as follows:
@interface xypoint:nsobject<nscopying>
- Copywithzone: Method Implementation:
– (ID) Copywithzone: (Nszone *) Formal method in zone//nscopying protocol
{
Xypoint *newpoint =[[xypoint Allocwithzone:zone] init];
[Newpoint setx:x andy:y];//Copy An instance variable of an old object into a new object
X and Y: is an instance variable of the old object to be copied
return newpoint;
}
Category Trial Range:
- 1. When you have encapsulated a class, do not want to change it, but as the program functions, you need to add a method in the class, there is no need to modify the main class, only need to add a classification to the original class.
- 2. Split a large class into different classifications and implement declarative methods in different classifications, so that the implementation of a class can be written into multiple. m files for easy management and collaborative development.
Only methods can be added to the taxonomy, and instance variables cannot be added.
The methods in the classification have a higher precedence than the methods in the original class.
Summary of agreements and classifications in OBJECTIVE-C