Protocol --- instance, protocol ---
Protocol: declare some required methods and select implementation methods to declare some methods, that is, a Protocol is composed of a series of method declarations.
Step for creating a protocol file: place the mouse over the file list and use the shortcut key command + N to obtain
LamcoProtocol. h file
# Import <Foundation/Foundation. h> @ protocol lamcoProtocol <NSObject> @ required // required method-(void) study; @ optional // method that cannot be implemented-(void) work; @ end
LamcoProtocol. h file
#import <Foundation/Foundation.h>@protocol bankProtocol <NSObject>-(void)giveme;@end
Student. h file
#import <Foundation/Foundation.h>#import "lamcoProtocol.h"#import "bankProtocol.h"@interface Student : NSObject<lamcoProtocol,bankProtocol>@end
Student. m file
# Import "Student. h" @ implementation Student-(void) study {NSLog (@ "class on time every day, review, preview! ") ;}- (Void) work {NSLog (@" schedule a technical position for you ");}-(void) giveme {NSLog (@ "monthly pay-as-you-go");} @ end
OtherStudent. h file
#import <Foundation/Foundation.h>@interface OtherStudent : NSObject@end
OtherStudent. m file
#import "OtherStudent.h"@implementation OtherStudent@end
Main. m file
# Import <Foundation/Foundation. h> # import "Student. h "# import" OtherStudent. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * stu = [Student new]; // determine whether there is a blue branch protocol if ([stu conformsToProtocol: @ protocol (lamcoProtocol)]) {// determine whether the protocol has this method if ([stu respondsToSelector: @ selector (study)]) {[stu study]; [stu work];} else {NSLog (@ "");}} else {NSLog (@ "no training");} if ([stu conformsToProtocol: @ protocol (bankProtocol)]) {if ([stu respondsToSelector: @ selector (giveme)]) {[stu giveme];} else {NSLog (@ "no credibility") ;}} else {NSLog (@ "cannot attend iOS training ");} otherStudent * other = [OtherStudent new]; if ([other conformsToProtocol: @ protocol (lamcoProtocol)]) {if ([other respondsToSelector: @ selector (study)]) {NSLog (@ "Welcome to lanke");} else {NSLog (@ "do not want to attend training") ;}} return 0 ;}
Running result: