A common problem in OC programs is that a class wants other classes to help implement certain methods and then return the results to the class, and how can a class find a proxy to implement the method it wants?
This requires a protocol so that other classes that can comply with the protocol can implement the method declaration in the Protocol and become the proxy for that class.
protocol principles of Use :
1. Can be used to declare many methods, but cannot declare member variables.
2. As long as a class complies with this protocol, it is equivalent to having all of the method declarations in this Protocol and then implementing it in its own. m file.
3. As long as the parent complies with this protocol, it is equivalent to the subclass.
How to use protocol:
I. Definition OF the agreement
@protocol Agreement name <NSObject>
Method declaration
@end
Ii. how to comply with the agreement
1. Class Compliance Agreement
@interface Class Name: Parent class name < protocol 1, Protocol 2,......>
@end
2. Agreement to comply with agreements
@protocol protocol Name < Protocol 1, Protocol 2,......>
@end
Iii. keywords for method declarations in the agreement
[Email protected] (default), this is the default requirement to implement, do not implement there will be a warning.
[email protected] This can be implemented first or can not be implemented.
In general, these two keywords are used for communication between programmers, declaring which methods do not implement which methods are to be implemented.
When defining a variable, you can limit the object to which the variable is stored to comply with a protocol
Class name < protocol name >* variable name; such as Person<protocol1>*p=[[person Alloc]init]; The object required to save p must abide by the PROTOCOL1 protocol.
id< protocol name > variable name; such as id<protocol1>obj;
V. The attributes declared in the @property can also be a limitation of compliance with the agreement.
@property (Nonatomic, Strong) class name < protocol name > variable name, such as @property (Nonatomic,strong) person<protocol1>*p1;
Vi. the agreement can be defined not only in a separate. h file, but also in a declaration of a class.
The even if protocol content is common to be defined in a separate. h file for ease of use.
Vii. Advance declaration of the agreement
Similar to the early declaration of the class "@class class name", the advance declaration of the Agreement may be declared in the manner of "@protocol agreement name", some statements are purely statements, and if the methods required in the agreement need
Gets the method declaration #import the protocol header file.
such as: @protocol MyProtocol; #import "Myprotocol.h"
About protocol theory know that I only learn so much, in the future study to add it.
http://www.itheima.com/
Dark Horse Programmer--a summary of the protocol