The role of the Protocol is similar to the multiple inheritance of abstract base classes in C + +. Similar to the concept of an Interface (interface) in Java.
A protocol is a list of methods that are shared by multiple classes, and the methods listed in the Protocol are not implemented in this class, but are other classes that implement these methods.
If a class is to adhere to a protocol, the class must implement all the methods of a particular protocol (except for optional methods).
Defining a protocol requires the use of the @protocol directive, followed by the protocol name, and then you can declare some methods, and the declarations of all methods before the instruction @end are part of the protocol. As follows:
[CPP]View Plaincopy
- @protocol nscopying
- -(ID) Copywithzone: (nszone*) zone;
- @end
If your class decides to abide by the Nscopying protocol, you must implement the Copywithzone method. By listing the name of the protocol in a pair of angle brackets in @interface, tell the compiler that you are following a protocol such as:
@interface Test:nsobject <NSCopying>
Instance:
Fly.h
[CPP]View Plaincopy
- #import <Foundation/Foundation.h>
- @protocol Fly
- -(void) go;
- -(void) stop;
- @optional
- -(void) sleep;
- @end
FlyTest.h
[CPP]View Plaincopy
- #import <Foundation/Foundation.h>
- #import "Fly.h"
- @interface flytest:nsobject<fly> {
- }
- @end
Flytest.m
[CPP]View Plaincopy
- #import "FlyTest.h"
- @implementation Flytest
- -(void) go {
- NSLog (@"Go");
- }
- -(void) Stop {
- NSLog (@"Stop");
- }
- @end
Test.m
[CPP]View Plaincopy
- #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 results of the program run as follows:
Go
Stop
The standard syntax for @protocol is:
@protocol Agreement name < other agreements, ...>
Method declaration 1
@optional
Method Declaration 2
@required
Method Declaration 3
...
@end
@optional indicates that the class of the Protocol does not necessarily implement the method.
@required is a method that must be implemented.
OBJECTIVE-C Protocol (Protocol)