什么是代理,如何实现的?
委托代理(degegate),顾名思义,把某个对象要做的事情委托给别的对象去做。那么别的对象就是这个对象的代理,代替它来打理要做的事。
SecondPageControl.m
执行方(被委托的):
SecondViewThirdSubViewController.h
SecondViewThirdSubViewController.m
委托代理(degegate),顾名思义,把某个对象要做的事情委托给别的对象去做。那么别的对象就是这个对象的代理,代替它来打理要做的事。
反映到程序中, 首先要明确一个对象的委托方是哪个对象,委托所做的内容是什么。
委托者:
SecondPageControl.h
#import <UIKit/UIKit.h>
//委托的声明,设置委托者的名称 =1=
@protocol SecondPageControlDelegate <NSObject>
-(void)pushControllerTest:(id)dender;
//委托者需要实现方法pushControllerTest的声明 =2=
@end
@interface SecondPageControl : UIViewController<UIScrollViewDelegate>
{
....................
....................
....................
id<SecondPageControlDelegate>delegate; //=3=
}
@property (nonatomic, retain)id<SecondPageControlDelegate>delegate; //=4=
@endSecondPageControl.m
#import "SecondPageControl.h"
@interface SecondPageControl
...........................................
@end
@implementation SecondPageControl
@synthesize delegate; //=5=
//按钮响应事件
-(void) btnPressed:(id) sender
{
UIButton *myBtn=(UIButton *) sender;
if (myBtn.tag == 321) //因为消息不能直接发送到,所以使用代理
{
if([delegate respondsToSelector:@selector(pushControllerTest:)]) //委托者需要实现的方法pushControllerTest =6=
{
[delegate performSelector:@selector(pushControllerTest:) withObject:nil];
}
}
}执行方(被委托的):
SecondViewThirdSubViewController.h
#import <UIKit/UIKit.h>
@class SecondPageControlDelegate; //=1=
@interface SecondViewThirdSubViewController : UIViewController<SecondPageControlDelegate> //=2=
{
..........................
}
@endSecondViewThirdSubViewController.m
#import "SecondViewThirdSubViewController.h"
@implementation SecondViewThirdSubViewController
...............................
-(void)pushControllerTest:(id)sender //实现被委托的方法=3=
{
ImageShowController *imageShowView = [[[ImageShowController alloc] init] autorelease];
[self.navigationController pushViewController:imageShowView animated:NO];
}
@end
本文深入探讨了代理模式的概念,解释了其背后的原理,并通过具体实例展示了如何在程序中实现代理模式。从委托者与执行方的角色分配,到方法调用的细节,本文提供了全面的指导。
的理解和使用示例&spm=1001.2101.3001.5002&articleId=7950229&d=1&t=3&u=9182b513b66c46a399ef89618cd117c6)
672

被折叠的 条评论
为什么被折叠?



