今天模拟Button的delegate来联系一下protocol。
Button类
// Button.h // Protocal // // Created by WildCat on 13-7-24. // Copyright (c) 2013年 wildcat. All rights reserved. // #import <Foundation/Foundation.h> @class Button; //定义一个协议 @protocol ButtonDelegate <NSObject> -(void)onclick:(Button *) button; @end //定义一个类 如果要作为Button的代理一定要实现ButtonDelegate @interface Button : NSObject @property (nonatomic,retain) id<ButtonDelegate> delegate; -(void)click; @end
#import "Button.h" @implementation Button -(void)dealloc{ //释放_gelegate [_delegate release]; [super dealloc]; } -(void)click{ NSLog(@"调用onclick方法"); [_delegate onclick:self]; } @end
ButtonListener类
/ ButtonListener.h // Protocal // // Created by WildCat on 13-7-24. // Copyright (c) 2013年 wildcat. All rights reserved. // #import <Foundation/Foundation.h> @protocol ButtonDelegate; @interface ButtonListener : NSObject <ButtonDelegate> @end
#import "ButtonListener.h" #import "Button.h" @implementation ButtonListener -(void)onclick:(Button *)button{ NSLog(@"Button %@ 被点击",button); } @end
主函数:
// // main.m // Protocal // // Created by WildCat on 13-7-24. // Copyright (c) 2013年 wildcat. All rights reserved. // #import <Foundation/Foundation.h> #import "Button.h" #import "ButtonListener.h" int main(int argc, const char * argv[]) { @autoreleasepool { Button *button=[[[Button alloc] init] autorelease]; Button *button2=[[[Button alloc] init] autorelease]; ButtonListener *listener=[[[ButtonListener alloc] init] autorelease]; button.delegate=listener; button2.delegate=listener; [button click]; [button2 click]; } return 0; }
运行结果:
2013-07-24 16:49:41.344 Protocal[1380:303] 调用onclick方法
2013-07-24 16:49:41.346 Protocal[1380:303] Button <Button: 0x100109990> 被点击
2013-07-24 16:49:41.347 Protocal[1380:303] 调用onclick方法
2013-07-24 16:49:41.347 Protocal[1380:303] Button <Button: 0x1001099e0> 被点击