下面以 屏幕的触摸时间为例说一下委托模式。
首先是建了一个协议Action,定义一个doAction的方法:
#import <Cocoa/Cocoa.h>
@protocol Action <NSObject>
-(void) doAction;
@end
定义一个屏幕的接口 ,有一个Action类型的变量delegage (这是一个委托对象,就是将事件委托这个对象来处理)
@interface Screen : NSObject <Action>{
id <Action> delegage;}
@property(nonatomic,retain) id<Action> delegage;-(void)onTouch;
@end
下面是实现类:
#import "Screen.h"
#import "Action.h"@implementation Screen
@synthesize delegage;
-(void) doAction{
NSLog(@"Bang !!!!");
}-(void) onTouch{
NSLog(@" onTouch start");
if ([delegage conformsToProtocol:@protocol(Action)] && [ delegage respondsToSelector:@selector(doAction)]) {
[delegage performSelector:@selector(doAction)];
}
NSLog(@"onTouch end ");
}@end
下面代码是判断delegage对象中是否继承了Action协议,并且 判断对象中是否有doAction方法,如果条件成立 就执行doAction方法
if ([delegage conformsToProtocol:@protocol(Action)] && [ delegage respondsToSelector:@selector(doAction)]) {
[delegage performSelector:@selector(doAction)];
}
下面是主方法用来对上面代码进行测试:
int main (int argc, const char * argv[]) {
Screen * screen=[[Screen alloc]init];
screen.delegage=screen;
[screen onTouch];
}