要求:用协议模拟实现按钮的点击事件
Button.h
#import <Foundation/Foundation.h> @class Button; //<>表示实现了某个协议 @protocol ButtonDelegate <NSObject> -(void)onClick:(Button *)btn; @end @interface Button : NSObject //delegate就是按钮的监听器 <>里面就是指上面的那个协议 @property(nonatomic,retain) id<ButtonDelegate> delegate; -(void)click; @end
Button.m:
#import "Button.h" @implementation Button -(void)click{ //如果delegate实现了onclick:这个方法 if([_delegate respondsToSelector:@selector(onClick:)]) { //按钮被点击了,就应该通知监听器 [_delegate onClick:self]; } else { NSLog(@"监听器并没有实现onClick:方法"); } } -(void)dealloc{ [_delegate release]; [super dealloc]; } @end
MyListener.h:
#import <Foundation/Foundation.h> #import "Button.h" @interface MyListener : NSObject<ButtonDelegate> @end
MyListener.m:
#import "MyListener.h" #import "Button.h" @implementation MyListener -(void)onClick:(Button *)btn{ NSLog(@"已经监听到按钮:%@点击了",btn); } @end
ButtonListener.h:
#import <Foundation/Foundation.h> #import "Button.h" //一个类要遵守一个协议,要用<>来添加协议名称 @interface ButtonListener : NSObject<ButtonDelegate> @end
ButtonListener.m:
#import "ButtonListener.h" @implementation ButtonListener -(void)onClick{ NSLog(@"按钮被点击了"); } @end
Main:
#import <Foundation/Foundation.h> #import "Button.h" #import "ButtonListener.h" #import "MyListener.h" int main(int argc, const char * argv[]) { @autoreleasepool { //初始化一个按钮 Button *btn=[[[Button alloc] init] autorelease]; //初始化一个按钮监听器 ButtonListener *btnListener=[[[ButtonListener alloc] init] autorelease]; MyListener * mylisten=[[[MyListener alloc] init] autorelease]; //将这个监听器给按钮 btn.delegate=btnListener; [btn click]; NSLog(@"当前按钮是%@",btn); btn.delegate=mylisten; [btn click]; } return 0; }
结果:
2013-08-02 14:47:26.352 Protocol[656:303] 监听器并没有实现onClick:方法
2013-08-02 14:47:26.353 Protocol[656:303] 当前按钮是<Button: 0x100109940>
2013-08-02 14:47:26.354 Protocol[656:303] 已经监听到按钮:<Button: 0x100109940>点击了
时间: 2024-10-14 22:52:45