前言:
因为Object-C是不支持多继承的,所以很多时候都是用Protocol(协议)来代替。Protocol(协议)只能定义公用的一套接口,但不能提供具体的实现方法。也就是说,它只告诉你要做什么,但具体怎么做,它不关心。
当一个类要使用某一个Protocol(协议)时,都必须要遵守协议。比如有些必要实现的方法,你没有去实现,那么编译器就会报警告,来提醒你没有遵守××协议。注意,我这里说的是警告,而不是错误。对的,就算你不实现那些“必要实现”的方法,程序也是能运行的,只不过多了些警告。
Protocol(协议)的作用:
1. 定义一套公用的接口(Public)
@required:必须实现的方法
@optional:可选 实现的方法(可以全部都不实现)
2. 委托代理(Delegate)传值:
它本身是一个设计模式,它的意思是委托别人去做某事。
比如:两个类之间的传值,类A调用类B的方法,类B在执行过程中遇到问题通知类A,这时候我们需要用到代理(Delegate)。
又比如:控制器(Controller)与控制器(Controller)之间的传值,从C1跳转到C2,再从C2返回到C1时需要通知C1更新UI或者是做其它的事情,这时候我们就用到了代理(Delegate)传值。
3.使用Delegate页面传值
在写代码之前,先确定一下要实现的功能:
VCA:
VCB:
- 视图从视图控制器A跳转到视图控制器B
- 将视图控制器B上textField的值传递给视图控制器A的Label.
然后再思考一下协议的写法.
在被弹出的VC(也就是VCB)中定义delegate,在弹出VC(也就是VCA)中实现该代理.
下面来看一下代码:
1.在VCB中新建一个协议,协议名一般为:类名+delegate
并且设置代理属性
VCB.h文件
#import <UIKit/UIKit.h>
@protocol ViewControllerBDelegate <NSObject>
- (void)sendValue:(NSString *)string;
@end
@interface ViewControllerB : UIViewController
// 委托代理,代理一般需使用弱引用(weak)
@property(nonatomic, weak) id<ViewControllerBDelegate>delegate;
@end
2.在VCA中签署协议
VCA.h文件
#import <UIKit/UIKit.h>
#import "ViewControllerB.h"
@interface ViewController : UIViewController <ViewControllerBDelegate>
@end
3.在VCA中实现协议方法,并设置VCB的代理
VCA.m文件
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation ViewController
//跳转按钮事件
- (IBAction)buttonAction:(UIButton *)sender {
ViewControllerB *vcB = [[ViewControllerB alloc] init];
//设置vcB的代理
vcB.delegate = self;
//跳转到vcB
[self.navigationController pushViewController:vcB animated:YES];
}
//实现协议方法
- (void)sendValue:(NSString *)string {
_label.text = string;
}
@end
4.在VCB中调用代理方法
VCB.m文件
#import "ViewControllerB.h"
@interface ViewControllerB ()
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewControllerB
//back按钮点击事件
- (IBAction)buttonAction:(UIButton *)sender {
//调用代理方法
[_delegate sendValue:_textField.text];
//跳转回vcA
[self.navigationController popToRootViewControllerAnimated:YES];
}
@end
小结:
这样写的好处是:VCB中不需要关联VCA,就能够实现值的传递.