Objective-c 协议(protocol)

协议的作用类似地C++中对抽象基类的多重继承。类似于Java中的接口(interface)的概念。
  协议是多个类共享方法的列表,协议中列出的方法在本类中并没有相应实现,而是别的类来实现这些方法。

  如果一个类要遵守一个协议,该类就必须实现特定协议的所有方法(可选方法除外).

  定义一个协议需要使用@protocol指令,紧跟着的是协议名称,然后就可以声明一些方法,在指令@end之前的所有方法的声明都是协议的一部分。如下:

  1. @protocol NSCopying  
  2. -(id) copyWithZone:(NSZone*) zone;  
  3. @end  


如果你的类决定遵守NSCopying协议,则必须实现copyWithZone方法。通过在@interface中的一对尖括号内列出协议的名称,告诉编译你正在遵守一个协议,比如:
@interface Test:NSObject <NSCopying>

实例:
Fly.h

  1. #import <Foundation/Foundation.h>  
  2. @protocol Fly  
  3.   -(void) go;  
  4.   -(void) stop;  
  5. @optional  
  6.   -(void)sleep;  
  7. @end  


FlyTest.h

  1. #import <Foundation/Foundation.h>  
  2. #import "Fly.h"  
  3. @interface FlyTest:NSObject<Fly> {  
  4. }  
  5. @end  


FlyTest.m

  1. #import "FlyTest.h"  
  2. @implementation FlyTest  
  3. -(void) go {  
  4.    NSLog(@"go");  
  5. }  
  6. -(void) stop {  
  7.    NSLog(@"stop");  
  8. }  
  9. @end  


test.m

  1. #import <Foundation/Foundation.h>  
  2. #import "FlyTest.h"  
  3. int main( int argc, char* argv[]){  
  4.   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];  
  5.   FlyTest *flytest = [[FlyTest alloc]init];  
  6.   [flytest go];  
  7.   [flytest stop];  
  8.   [flytest release];  
  9.   
  10.   [pool drain];  
  11.   return 0;  
  12. }  


程序运行结果如下:

go
stop


@protocol的标准语法是:
@protocol 协议名<其它协议, …>
  方法声明1
@optional
  方法声明2
@required
  方法声明3

@end


@optional表明该协议的类并不一定要实现方法。
@required是必须要实现的方法。



原文地址:https://www.cnblogs.com/Free-Thinker/p/4962976.html