我说很难是对我这个初学者来说的,哈哈。看了几天OC 的委托,查了些资料还是很迷糊,不知下面这种理解是否正确。请指点
- C/C++ code
#import <Foundation/Foundation.h>#import "TView.h"#import "TActive.h"int main(int argc, const char * argv[]){ @autoreleasepool { TView * v = [[TView alloc] init]; TActive * a = [[TActive alloc] init]; a.tView = v; v.Delegate = a; [v onClick]; } return 0;}TView.h文件:@protocol Message <NSObject> -(void) onClickMsg;@end@interface TView : NSObject <Message>{ NSString * TViewText; id <Message> Delegate; }@property (nonatomic,retain) id <Message> Delegate;@property (nonatomic,retain) TView * TviewText;- (void) onClick;- (TView *) init;- (void) Show;@endTView.m文件:#import "TView.h"@implementation TView@synthesize Delegate;@synthesize TviewText;-(TView *)init{ self = [super init]; if(self) { NSLog(@"上网请点击我"); } return self;}-(void)onClick{ NSLog(@"按键被点击。"); [Delegate onClickMsg]; }-(void) Show{ NSLog(@"已从网路上下载了数据。我将显示它"); NSLog(@"从网路上下载的数据是:%@",TviewText); NSLog(@"显示完毕谢谢使用。再见!");}@endTActive.h文件#import <Foundation/Foundation.h>#import "TView.h"@interface TActive : NSObject <Message>{ TView * tView;}@property (nonatomic,retain) TView * tView;@endTActive.m文件#import "TActive.h"@implementation TActive@synthesize tView;-(void) onClickMsg{ NSLog(@"从网路上下载数据。"); NSLog(@"下载的数据是:中国"); [tView setTviewText:@"中国"]; NSLog(@"下载完毕。"); [tView Show];}@end
------解决方案--------------------
协议说白了就是一种契约。需要交互的双方遵守的一种约束。而这里提到的是“代理协议”概念,这应该是一种解决对象交互解藕的一种设计模式。比如如下场景:有两个对象A和B,A中一个方法需要调用B中一方法,我们通常会在A中添加B的指针应用,这样做没有问题,但是有可能我们在B的对象中还需要调用A的方法,如果还按这种设计,很可能会出现循环引用。
其实对象在交互的过程无非承担二种角色,1.数据接收者,2.数据发送者。在“代理协议”这个模型中,数据发送者包含数据接收者的指针。
@interface MyWidget:BaseWidget {
? id<BaseWidgetDelegate> delegate;
}
@property (assign) id <BaseWidgetDelegate> delegate;
@end
而数据接收者则需要实现协议
@protocal BaseWidgetDelegate;
@interface WidgetManager:NSObject<BaseWidgetDelegate>
? ....
@end