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

什么是代理,如何实现的?


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值