Day16 oc protocol

use of protocol

Create file, select object c - protocol, only .h file

 

@protocol Myprotocol
{
-(void)test1;
@required//By default, it is required to be implemented. If it is not implemented, a warning will be issued to facilitate collaborative communication (different from the interface in java, which will report an error if it is not implemented)
-(void)test2;
@optional//Does not require implementation
-(void)test3;
}
Protocol keywords: required, optional

 

Used to declare methods, classes want to have these methods, just abide by this protocol

 

#import “MyProtocol.h”
//: inherit <> obey the protocol
@interface Person:NSObject <MyProtocol>
@end
Implement the method in the .m file
@implementation Person
-(void)test1
{
}
-(void)test2
{
}
@end
 Therefore, the basic use of the protocol 1. It can be used to declare a lot of methods, but cannot declare member variables. 2. As long as the class complies with this protocol, it is equivalent to having the declaration of all methods of this protocol. 3. As long as the parent class complies with this protocol, it is equivalent to Subclasses also obey

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326924611&siteId=291194637