Protocol: Protocol
Want to have some method declarations by:
: Inherit parent class
<> Compliance Agreements
Protocol: It is used to declare a method, to have some method declaration, only need to abide by the protocol.
1. Definition of the Agreement
@protocol Agreement name <NSObject>
method declaration list ....
@end
// defines a protocol called MyProtocol @protocol myprotocol <NSObject>// @required Requires implementation, does not implement will issue a warning (default is this)// @optional does not require implementation -(void) test4; @required- (void) test; -(void) test2; @optional-(void) test3; @end
2. How to comply with the agreement
1> Class Compliance Agreement
@interface class Name: parent class name < protocol Name 1, protocol name 2>
@end
2> Protocol Compliance Agreement
@protocol Agreement name < other protocol name 1, other protocol name 2>
@end
Attention:
One protocol can also comply with another protocol, and you can have all the method declarations of another protocol
@protocol MyProtocol1 <myprotocol>
3. Keywords for method declarations in the agreement
1> @required ( default)
Requires implementation, and if not implemented, a warning is issued
2> @optional
Does not require implementation, how can there be no warning
4. When defining a variable, limit the object that this variable holds to a protocol
Class name < protocol name > * variable name ;
id< protocol name > variable name;
Nsobject<myprotocol> *obj;
Id<myprotocol> Obj2;
If the corresponding protocol is not followed, the compiler warns
// have a proxy attribute // ID on behalf of the proxy class name casually // but must comply with the Ticketdelegate protocol ID delegate;
the attributes declared in [email protected] can also be used as a limit to comply with the agreement
@property (nonatomic, strong) class name < protocol name > * attribute name;
@property (nonatomic, Strong) id< protocol name > attribute name;
@property (nonatomic, strong) dog<myprotocol> *dog;
@property (nonatomic, strong) id<myprotocol> dog2;
6. The agreement can be defined in a separate. h file and can also be defined in a class
1> If this protocol is used only in a class, the protocol should be defined in that class
2> If this protocol is used in many classes, it should be defined in a separate file
7. Classifications can be defined in separate . h and . m files and can also be defined in the original class
1> in general, are defined in a separate file
2> defines the classification in the original class, only requires the ability to read the grammar
iOS development OC (14)--protocol Protocol (1)