Objective-c 协议(protocol)

来源:互联网 发布:淘宝店铺动态评分规则 编辑:程序博客网 时间:2024/05/16 09:25
  协议的作用类似地C++中对抽象基类的多重继承。类似于Java中的接口(interface)的概念。
  协议是多个类共享方法的列表,协议中列出的方法在本类中并没有相应实现,而是别的类来实现这些方法。

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

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

@protocol NSCopying-(id) copyWithZone:(NSZone*) zone;@end

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

实例:
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;}

程序运行结果如下:

go
stop


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

@end



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



原创粉丝点击