iOS 委托模式


委托Delegate是协议的一种,通过一种@protocol的方式实现,顾名思义,就是委托他人帮自己去做什么事。也就是当自己做什么事情不方便的时候,就可以建立一个委托,这样就可以委托他人帮自己去实现什么方法。


简单的总结了一下自己用到的 委托的作用有两个,一个是传值,一个是传事件。
1.所谓传值经常用在B类要把自己的一个数据或者对象传给A类,让A类去展示或者处理。(这个作用在两个View视图之间传递参数的时候特别有用) (例子一)
2.所谓传事件就是A类发生了什么事,把这件事告诉关注自己的人,也就是委托的对象,由委托的对象去考虑发生这个事件后应该做出什么反映。简单的说,假如A类发生某个事件,它本身并不出来,而是通过委托delegate的形式,让它的委托对象B类去处理(当然委托对象B就要实现委托中的方法)。 (例子二)
----下面都会有例子展示。

实现委托的过程中还要注意一些问题:

1、委托过程中需要定义协议@protocol ,这个协议可以单独New File成一个单独的协议文件,也可以放在委托对象的头文件中,一般的习惯是后者。

2、在协议中定义委托对象需要委托别人处理的一些方法,用于传值或者传事件。

3、委托类中需要定义一个协议的实例对象,注意属性一般设置为assign而非retain(一般命名为delegate,但是注意假如给类中原本就又这个属性,就要换一个名字,通过这个协议实例对象就可以调用协议中的方法(即委托方法)。

4、被委托类中需要在自身的interface中声明协议:<XXXDelegate>,表示该类要实现XXXDelegate协议中的方法。

5、注意最后要把委托类对象的delegate设置为被委托类对象,一般的处理有两种方法:

委托类对象.delegate = 被委托类对象

②在被委托类里定义一个委托类对象,并设置委托类对象.delegate = self (例子三)

下面通过三个例子demo就可以更生动的体会了。

一、通过委托传值

下面简要说明一下这个例子:

委托类是:Customer,其中委托协议中定义了一个方法,该方法表示customer要买一个iphone(会传递一个iphone型号参数),customer通过委托delegate调用这个方法表示customer要买iphone。

被委托类是:Businessman,其继承这个协议,实现了协议中的方法,也即处理了委托类customer要买iphone的需要。

下面贴代码:

Customer.h

#import <Foundation/Foundation.h>

@protocol MyDelegate <NSObject>

-(void)buyIphone:(NSString*)iphoneType;

@end

@interface Customer : NSObject

@property(nonatomic,assign)id<MyDelegate> delegate;

-(void)willBuy;

@end

Customer.m

#import "Customer.h"

@implementation Customer

@synthesize delegate;

-(void)willBuy {
    [delegate buyIphone:@"Iphone5"];
}

@end

Businessman.h

#import <Foundation/Foundation.h>
#import "Customer.h"

@interface Businessman : NSObject<MyDelegate>

@end

Businessman.m

#import "Businessman.h"

@implementation Businessman

-(void)buyIphone:(NSString *)iphoneType {
    NSLog(@"There is an Iphone store,we have %@",iphoneType);
}


@end

main.m

#import <Foundation/Foundation.h>

#import "Customer.h"
#import "Businessman.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Customer *customer = [[Customer alloc]init];        
        Businessman *businessman = [[Businessman alloc]init];
        customer.delegate = businessman;
        [customer willBuy];
    }
    return 0;
}

二、通过委托传事件

下面也是简单说一下这个例子:

委托类:Boss 他要处理起草文件和接电话的任务,但是他本身并不实现这些事件响应的方法,而是通过委托让他的被委托类来实现这些响应方法。

被委托类:Secretary 他受Boss的委托实现起草文件和接电话任务的方法。

下面贴代码:

Boss.h

#import <Foundation/Foundation.h>

@protocol MissionDelegate <NSObject>

-(void)draftDocuments;

-(void)tellPhone;

@end

@interface Boss : NSObject

@property(nonatomic, assign)id<MissionDelegate> delegate;

-(void)manage;

@end

Boss.m

#import "Boss.h"

@implementation Boss

@synthesize delegate = _delegate;

-(void)manage {
    [_delegate draftDocuments];
    [_delegate tellPhone];
}
@end

Secretary.h

#import <Foundation/Foundation.h>
#import "Boss.h"
@interface Secretary : NSObject <MissionDelegate>

@end

Secretary.m

#import "Secretary.h"

@implementation Secretary

-(void)draftDocuments {
    NSLog(@"Secretary draft documents");
}

-(void)tellPhone {
    NSLog(@"Secretary tell phone");
}

@end

main.m

#import <Foundation/Foundation.h>
#import "Secretary.h"
#import "Boss.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Boss *boss = [[Boss alloc] init];
        Secretary *secretary =  [[Secretary alloc] init];
        
        boss.delegate = secretary;
        [boss manage];
    }
    return 0;
}

三、这个例子两个view视图之间传递参数

定义一个MyView类,在这个视图中添加了一个button,button的事件响应他本身不处理,而让被委托类去处理,所以它就是委托类。

在主视图中,添加一个MyView类的实例对象,设置该实例对象的代理为self,所以它就是委托类了。

下面还是贴代码,应该都是很容易看懂的。

MyView.h

#import <UIKit/UIKit.h>

@protocol MyDelegate <NSObject>

-(void)print:(NSString*)viewName;

@end

@interface MyView : UIView

@property(nonatomic,assign)id<MyDelegate> mydelegate;

@end

MyView.m

#import "MyView.h"

@implementation MyView


@synthesize mydelegate = _mydelegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        //代码创建一个button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:@"Button" forState:UIControlStateNormal];
        [button setFrame:CGRectMake(10, 10, 100, 50)];
        [button setTintColor:[UIColor blueColor]];
        
        //Target-Action模式   为button指定事件处理对象target为self,事件处理方法为buttonPressed
        [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
    }
    return self;
}
//事件处理的响应方法
-(void)buttonPressed{
    
    [_mydelegate print:@"this is a view"];
}

@end

DelegateViewController.h

#import <UIKit/UIKit.h>
#import "MyView.h"

@interface DelegateViewController : UIViewController<MyDelegate>

@end

DelegateViewController.m

#import "DelegateViewController.h"

@interface DelegateViewController ()

@end

@implementation DelegateViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    MyView *myView = [[MyView alloc]initWithFrame:CGRectMake(50, 100, 200, 100)];
    [myView setBackgroundColor:[UIColor yellowColor]];
    myView.mydelegate = self;
    [self.view addSubview:myView];
}

-(void)print:(NSString *)viewName {
    NSLog(@"%@",viewName);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

ok,研究了一个上午,大致算是弄懂了吧! 大笑

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值