protocol——协议 协议是用来定义对象的属性,行为和用于回调的。 协议中有两个关键字@private和@optional,@private表示使用这个协议必需要写的方法,@optional表示可选的方法,用不到能够不写。 就像UITableView,它有两个协议:UITableViewDelegate和UITableViewDataSource,UITableViewDelegate是规定行为操做的,里面的方法都是可选的方 法,UITableViewDataSource是规定数据存储结构的,有两个必选方法。所以你再实现UITableViewDataSource时必需要定义这两个方法,不然程序会出错。 若是你使用了响应的类或者控件,若是该类定义了协议,就能够根据须要实现该协议。 protocol和java里interface的概念相似,是Objective-C语法的一部分。 定义protocol以下 [cpp] view plaincopyprint? 1 2 3 4 5 6 @protocol ClassADelegate - (void)methodA; - (void)methodB; @end 那么就是定义了一组函数,这组函数放在一块儿叫做一个protocol,也就是协议。 函数是须要被实现的,因此若是对于class以下 [cpp] view plaincopyprint? @interface ClassB <ClassADelegate> { } @end 就叫做ClassB conform to protocol ClassADelegate,也就是说ClassB实现了这个协议, 也就是实现了这一组函数。 有了上面这个头文件,咱们就能够放心做调用 [cpp] view plaincopyprint? ClassB *b = [[ClassB alloc] init]; [b methodA]; [b methodB]; 而不用担忧出现unrecognized selector sent to instance这种错误了。 因此protocol就是一组函数定义,是从类声明中剥离出来的一组定义。 [cpp] view plaincopyprint? id<ClassADelegate> b = ...; [b methodA]; 这种用法也常见,b是一个id类型,它知道ClassADelegate这组函数的实现。 delegate——委托,代理 适用场合: 类A调用类B, 当类B想回调类A的方法的时候, 要用到delegate 要理解下面的代码的话, 要知道的一个知识点是 协议(protocal) 文件:ClassA.h #import <Foundation/Foundation.h> #import "ClassB.h" @interface ClassA : NSObject<SampleProtocal> - (void)test; @end 文件:ClassA.m #import "ClassA.h" @implementation ClassA -(void)test{ ClassB *classB = [[ClassB alloc] init]; classB.delegate = self; [classB actionOfClassB]; } -(void)callback{ NSLog(@"这个方法会被类B调用"); } @end 文件:ClassB.h #import <Foundation/Foundation.h> @protocol SampleProtocal <NSObject> @required - (void)callback; @end @interface ClassB : NSObject{ id<SampleProtocal> delegate; } @property (nonatomic, retain) id<SampleProtocal> delegate; - (void)actionOfClassB; @end 文件:ClassB.m #import "ClassB.h" @implementation ClassB @synthesize delegate; -(void)actionOfClassB{ [delegate callback]; } @end 摘自:http://blog.csdn.net/mars2639/article/details/7310182
|