OC Protocol----协议

类似Java的泛型与接口的结合体,用于类型的<>中,可以多继承(按照OC的说法叫遵从某些协议)

1、定义协议

@protocol Client <NSObject>
-(void)defaultMethod;//默认必须实现 @required//必须
-(void)required; @optional//可选
-(void)optional;
@end

2、符合(实现)协议


#import "Client.h"
@interface JackClient : NSObject<Client> @end @implementation JackClient
-(void)defaultMethod{
NSLog(@"this is defaultMethod");
} -(void)required{
NSLog(@"this is required method");
}
@end

3、使用并调用回调

#import "Client.h"
#protocol JackClient @interface Test : NSObject<Client>{
id<Client> client;
}
-(id)initWithClient:(id<Client>) client;
-(void) turnTheCrank;
@property(retain) id<Client> client; @end @implementation Test -(id)initWithClient:(id<Client>)client{
self = [super init];
if (self) {
_client = client;
}
return self;
} -(void) turnTheCrank{
[self.client defaultMethod];
[self.client required];
if ([self.client respondsToSelector:@selector(optional)]) {//可选回调可先判断是否实现,再调用
[self.client optional];
}
} @end

最后

[[[Test alloc]initWithClient:[[JackClient alloc] init]] turnTheCrank];  
上一篇:windows nginx 搭建文件服务器(通俗易懂)


下一篇:VBoxManage.exe: error: Resize hard disk operation for this format is not implemented yet!