The role of the Protocol is similar to the multi-inheritance of abstract base classes in C ++. Similar to the interface concept in Java.
The Protocol is a list of multiple class sharing methods,Methods listed in the Protocol are not implemented in this class, but are implemented by other classes.
If a class complies with a protocol, the class must implement all methods of the specific Protocol (except for optional methods ).
To define a protocol, you need to use the @ protocol command, followed by the protocol name, and then you can declare some methods. The declaration of all methods before the command @ end is part of the Protocol. As follows:
@protocol NSCopying-(id) copyWithZone:(NSZone*) zone;@end
If your class decides to comply with the nscopying protocol, you must implement the copywithzone method. By listing the protocol name in a pair of angle brackets in @ interface, you are told to compile a protocol, for example:
@ Interface Test: nsobject <nscopying>
Instance:
Fly. h
#import <Foundation/Foundation.h>@protocol Fly -(void) go; -(void) stop;@optional -(void)sleep;@end
Flytest. h
#import <Foundation/Foundation.h>#import "Fly.h"@interface FlyTest:NSObject<Fly> {}@end
Flytest. m
#import "FlyTest.h"@implementation FlyTest-(void) go { NSLog(@"go");}-(void) stop { NSLog(@"stop");}@end
Test. m
#import <Foundation/Foundation.h>#import "FlyTest.h"int main( int argc, char* argv[]){ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; FlyTest *flytest = [[FlyTest alloc]init]; [flytest go]; [flytest stop]; [flytest release]; [pool drain]; return 0;}
The program running result is as follows:
Go
Stop
@ Protocol:
@ Protocol name <other protocols,...>
Method Declaration 1
@ Optional
Method Declaration 2
@ Required
Method 3
...
@ End
@ Optional indicates that the classes of the Protocol do not have to be implemented.
@ Required is a required method.