Objective-C与java一样,只支持单一继承,当需要创建一个类能表现多个类的特性时,需要采用与Java中类似的(接口)称为协议(Protocol)的方法。
如同一个类a,一个类b,两个类签订一个协议p,该p协议规定一个方法c,c的实现在b中,当a需要调用实现c时,并不调用类b,而是声明一个id<p> delegate, 如同a掏出一份协议交给代理商,然后delegate会去找到b,让其完成c这件事。
这样的调用更加干净,下面用一个例子具体说明一下:
protocol用法:
@interface ClassA :ClassB<protocol1, protocol2>
首先先来一个一般情况下的例子,声明一个UIView类:
@interface myView :UIView{
}
@end
之后再声明一个protocol,前缀为protocol,没有方法的实现(实现要交给别的类去完成):
@protocol myViewDelegate
-(void) Fun1;
-(void) Fun2;
@end;
之后就是代理委托人拉,委托的声明方式如下,我们要在ClassB内使用Fun1方法,但是不需要做声明:
@interface ClassB :UIViewController<myViewDelegate>
@end
ClassB实现:
@implement ClassB
-init{
MyView *view = [[MyView alloc]init];
view.delegate = self;
self.view = view;
}
-(void)Fun1{
//dostuff,like change navigatorBar blablabla
}
@end
那么怎么在ClassA中使用Fun1呢?需要在ClassA的声明中添加:
@interface myView :UIView{
id<myViewDelegate> delegate;
}
@property ...
@end
具体实现中时:
-doSth(){
[delegate Fun1];
}