4 9.OC15-Protocol
Protocol
1)、简单来说就是一系列方法的列表,其中声明的方法可以被任何类实现。这种模式一般称为代理(delegation)模式。
2)、在IOS和OS X开发中,Apple采用了大量的代理模式来实现MVC中view(UI控件)和Controller(控制器)的解耦。
Main.m
// // main.m // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-9. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h> #import "Button.h" #import "ButtonListener.h" #import "MyListener.h"
int main(int argc, const char * argv[]) {
@autoreleasepool { //初始化一个按钮 Button *button = [[[Button alloc] init] autorelease]; //初始化一个按钮的监听器 //ButtonListener *listener = [[[ButtonListener alloc] init] autorelease]; MyListener *listener = [[[MyListener alloc] init] autorelease];
//设置按钮的监听器 button.delegate = listener;
//点击按钮 [button click];
Button *button2 = [[[Button alloc] init] autorelease]; button2.delegate = listener; //点击button2 [button2 click]; } return 0; }
|
Button.h
// // Button.h // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h> @classButton;
// <>代表实现某个协议 @protocol ButtonDelegate <NSObject> - (void)onClick:(Button *)btn; @end
@interface Button : NSObject
// delegate 就是按钮的监听器 @property (nonatomic, retain) id<ButtonDelegate> delegate;
// 点击按钮 - (void)click;
@end
|
Button.m
// // Button.m // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. //
#import "Button.h"
@implementation Button
- (void)dealloc{ [_delegaterelease]; [super dealloc]; }
- (void) click{ //如果delegate实现了onClick:这个方法 if( [_delegate respondsToSelector:@selector(onClick:)]){ //按钮被点击了,就应该通知监听器,并且告诉监听器哪个按钮被点击了 [_delegate onClick:self]; }else{ NSLog(@"监听器并没有实现onClick:方法"); } }
@end |
ButtonListener.h
// // ButtonListener.h // OC10-内存管理2-set方法的内存管理 // // Created by liuyes on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h>
//#import "Button.h" //对协议进行提前声明,跟@class的用途是一致 @protocolButtonDelegate;
@interface ButtonListener : NSObject<ButtonDelegate>
@end |
ButtonListener.m
// // ButtonListener.m // OC10-内存管理2-set方法的内存管理 // // Created by liuyes on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. // #import "ButtonListener.h" #import "Button.h"
@implementation ButtonListener
- (void)onClick{ NSLog(@"ButtonListener已经监听到按钮被点击了"); }
@end |
MyListener.h
// // MyListener.h // OC10-内存管理2-set方法的内存管理 // // Created by liuyes on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h> //#import "Button.h" @protocolButtonDelegate;
@interface MyListener : NSObject <ButtonDelegate>
@end |
MyListener.m
// // MyListener.m // OC10-内存管理2-set方法的内存管理 // // Created by liuyes on 13-12-10. // Copyright (c) 2013年 renhe. All rights reserved. //
#import "MyListener.h" #import "Button.h"
@implementation MyListener
- (void)onClick{ NSLog(@"MyListener已经监听到按钮被点击了"); }
- (void)onClick:(Button *)btn{ NSLog(@"MyListener已经监听到按钮-%@被点击了", btn); }
@end |