關(guān)于delegate的理解:是一種設(shè)計(jì)模式即代理模式,可以去參考中介找房案例來理解代理模式,說一下個人的理解吧:我理解的代理模式就是我需要做一件事但是我又沒有時間或者有一部分條件并不具備,所以我需要別人來完成,而我需要告訴他我要做什么,至于如何讓完成是他的事情
代理最常用的的用法就是逆向傳值,下面通過一個小demo來看一下具體怎么用
實(shí)現(xiàn)的功能:我有兩個頁面,我先當(dāng)前VC: MeViewController 通過按鈕跳轉(zhuǎn)到下一個VC:TestViewController,該VC上面三個按鈕,每當(dāng)我點(diǎn)擊一個按鈕是退回到上一個VC,并且在 VC:?MeViewController 的label上顯示我點(diǎn)擊的按鈕是第幾個,即將我點(diǎn)擊的按鈕的值傳遞給上一個界面。
代碼實(shí)現(xiàn):
1.創(chuàng)建協(xié)議
//import "TestViewController.h":
@protocol TestViewControllerDelegate <NSObject>
// 讓協(xié)議方法帶參傳值
/**傳遞的值*/
- (void) showMeTarget:(NSInteger ) value;
@end
2.聲明委托變量
//import "TestViewController.h":
@interface TestViewController : UIViewController
@property (nonatomic, weak) id <TestViewControllerDelegate> delegate;
@end
至于為啥用weak 以后說到內(nèi)存管理再說
3.設(shè)置代理 因?yàn)槲沂窃贛eViewController里面跳轉(zhuǎn)的時候設(shè)置的,所以在MeViewController.h中
// #import "MeViewController.h"
- (void)jumpButtonDidClick {
? ? TestViewController *vc = [[TestViewController alloc]init];
? ? vc.title = @"跳轉(zhuǎn)頁面";
? ? vc.delegate = self;
? ? [self.navigationController pushViewController:vc animated:YES];
}
4.利用委托變量來調(diào)用協(xié)議方法,也就是將值傳遞過去讓代理者開始執(zhí)行協(xié)議
//import "TestViewController.h":
- (void) buttonDidClick:(UIButton *)btn {
? ? if([self.delegate respondsToSelector:@selector(showMeTarget:)])? ?{
? ? ? ? [self.delegate showMeTarget:btn.tag];
? ? }
? ? [self.navigationController popViewControllerAnimated:YES];
}
5.在代理MeViewController中遵守協(xié)議
@interface MeViewController ()<TestViewControllerDelegate,NSURLSessionDataDelegate>
@property (nonatomic,strong) UIButton *jumpButton;
@property (nonatomic,strong)UILabel *label;
@end
6.代理實(shí)現(xiàn)協(xié)議方法
- (void)showMeTarget:(NSInteger)value?{
? ? self.label.text = [NSString stringWithFormat:@"點(diǎn)擊了第%ld個按鈕",value];
}
嗯,看一下效果:


