iOS 设计模式-委托模式

时间:2023-03-08 21:48:53

委托是指给一个对象提供机会对另一对象中的变化做出反应或者相应另一个对象的行为。其基本思想是协同解决问题。

Delegate的使用场合

  • 对象A内部发生了一些事情,想通知对象B
  • 对象B想监听对象A内部发生了什么事情
  • 对象A想在自己的方法内部调用对象B的某个方法,并且对象A不能对对象B有耦合依赖
  • 对象A想传递数据给对象B

以上情况,结果都一样:对象B是对象A的代理(delegate)

在程序中使用

1.委托(A)需要做的工作有:

1.定义代理协议,协议名称的命名规范:控件类名 + Delegate
2.定义代理方法
  • 代理方法一般都定义为@optional
  • 代理方法名都以控件名开头
  • 代理方法至少有1个参数,将控件本身传递出去

3.设置代理(delegate)对象  (比如myView.delegate = xxxx;)

  • 代理对象遵守协议
  • 代理对象实现协议里面该实现的方法

4.在恰当的时刻调用代理对象(delegate)的代理方法,通知代理发生了什么事情

(在调用之前判断代理是否实现了该代理方法)

2.代理(B)需要做的工作有:

  • 遵循协议
  • 实现委托方法

实例:界面View底部点击"加载更多数据",通知控制器请求数据,并刷新表格。

委托A相关代码

定义代理协议、定义代理方法

#import <UIKit/UIKit.h>
@class TuangouFooterView; // 定义一个协议,控件类名 + Delegate
@protocol TuangouFooterViewDelegate <NSObject>
// 代理方法一般都定义为@optional
@optional
// 代理方法名都以控件名开头,代理方法至少有1个参数,将控件本身传递出去
-(void)tuangouFooterDidClickedLoadBtn:(TuangouFooterView *)tuangouFooterView; @end @interface TuangouFooterView : UIView // 定义代理。要使用weak,避免循环引用
@property(nonatomic,weak) id<TuangouFooterViewDelegate> delegate;
@end

在恰当的时刻调用代理对象(delegate)的代理方法,通知代理

 // 通知代理,先判断是否有实现代理的方法。
if ([self.delegate respondsToSelector:@selector(tuangouFooterDidClickedLoadBtn:)]) {
[self.delegate tuangouFooterDidClickedLoadBtn:self];
}

代理(B)相关代码

实现代理

@interface ViewController ()<TuangouFooterViewDelegate>

设置代理

    TuangouFooterView *footerView=[TuangouFooterView footerView];
footerView.delegate=self;// 设置当前footerView为代理

实现代理方法

/**
* 加载更多的数据
*/
- (void)tuangouFooterDidClickedLoadBtn:(TuangouFooterView *)tuangouFooterView
{
#warning 正常开发:发送网络请求给远程的服务器
// 1.添加更多的模型数据
Tuangou *tg = [[Tuangou alloc] init];
tg.icon = @"ad_01";
tg.title = @"新增加的团购数据..";
tg.price = @"";
tg.buyCount = @"";
[self.tgs addObject:tg]; // 2.刷新表格(告诉tableView重新加载模型数据, 调用tableView的reloadData)
[self.tableView reloadData];
}