委托代理(degegate)的理解和使用示例

来源:互联网 发布:菜刀连接数据库 编辑:程序博客网 时间:2024/05/28 17:06
什么是代理,如何实现的?


委托代理(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=@end

SecondPageControl.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={   ..........................}@end

SecondViewThirdSubViewController.m

#import "SecondViewThirdSubViewController.h"@implementation SecondViewThirdSubViewController...............................-(void)pushControllerTest:(id)sender  //实现被委托的方法=3={    ImageShowController *imageShowView = [[[ImageShowController alloc] init] autorelease];    [self.navigationController pushViewController:imageShowView animated:NO];}@end


原创粉丝点击