1 #import<Foundation/Foundation.h>2 #import "IOSProgrammer.h"3 #import "JavaCodingMonkey.h"4 intMainintargcConst Char*argv[]) {5 @autoreleasepool {6Javacodingmonkey * Javacodingmokey =[[Javacodingmonkey alloc] init];7 [Javacodingmokey Writejavacode];8 9Iosprogrammer * Iosprogrammer =[[Iosprogrammer alloc] init];Ten [Iosprogrammer sleep]; One [Iosprogrammer sing]; A [Iosprogrammer PlayGame]; - [Iosprogrammer Writeioscode]; - the ID<IOSProgrammerProtocol> staff =Iosprogrammer; - [Staff Writeioscode]; - - ID<IOSProgrammerProtocol> STAFF2 =Javacodingmokey; + [Staff2 Writeioscode]; - + //ID Type pointers can only invoke methods in the Protocol after complying with the Protocol A at - } - return 0; -}
main.m
1 #import<Foundation/Foundation.h>2 //name of the @protocol agreement <NSObject>3 @protocolIosprogrammerprotocol <NSObject>4@required//a method that must be implemented by default does not implement a warning5- (void) Writeioscode;6@optional//optional methods can be implemented or not implemented7- (void) Playtaiji;8 @end
IOSProgrammerProtocol.h
1 #import <Foundation/Foundation.h>2#import"IOSProgrammerProtocol.h "3@interface javacodingmonkey:nsobject<iosprogrammerprotocol>4 -(void) writejavacode; 5 @end
JavaCodingMonkey.h
1 #import "JavaCodingMonkey.h"2 3 @implementationJavacodingmonkey4- (void) Writejavacode {5NSLog (@"Write Java Code");6 }7 8- (void) Writeioscode {9NSLog (@"Write ISO Code");Ten } One @end
javacodingmonkey.m
1 #import<Foundation/Foundation.h>2 #import "IOSProgrammerProtocol.h"3 4 @interfaceIosprogrammer:nsobject<iosprogrammerprotocol>5- (void) sing;6- (void) sleep;7- (void) PlayGame;8 @end
IOSProgrammer.h
1 #import "IOSProgrammer.h"2 3 @implementationIosprogrammer4- (void) Sing {5NSLog (@"sang a fire gourd baby");6 }7 8- (void) Sleep {9NSLog (@"have a good rest.");Ten } One A- (void) PlayGame { -NSLog (@"played a League of legends."); - } the -- (void) Writeioscode { -NSLog (@"Write IOS Code"); - } + @end
IOSPROGRAMMER.M
Third, the application and function of the agreement
A. Application
1. (main function) specification interface (Protocol specification interface is mandatory)
2. Implement the principal-agent mechanism (implement communication between objects) Proxy design mode
B. function
- Protocol is to meet the unified data transmission
- A class can inherit only one direct parent class, but it implements multiple interfaces (following multiple protocols) and indirectly implements multiple inheritance.
Multi-inheritance can be defined by protocol multiple protocol classes are implemented by multiple protocol implementations.
The code is not written, it's simple.
Preliminary knowledge of Objective-c protocol