因为Object-C是不支持多继承的,所以很多时候都是用Protocol(协议)来代替。Protocol(协议)只能定义公用的一套接口,但不能提供具体的实现方法。也就是说,它只告诉你要做什么,但具体怎么做,它不关心。
当一个类要使用某一个Protocol(协议)时,都必须要遵守协议。比如有些必要实现的方法,你没有去实现,那么编译器就会报警告,来提醒你没有遵守××协议。注意,我这里说的是警告,而不是错误。对的,就算你不实现那些“必要实现”的方法,程序也是能运行的,只不过多了些警告。
Protocol(协议)的作用:
- 定义一套公用的接口(Public)
@required:必须实现的方法
@optional:可选 实现的方法(可以全部都不实现)
2. 委托代理(Delegate)传值:
它本身是一个设计模式,它的意思是委托别人去做某事。
比如:两个类之间的传值,类A调用类B的方法,类B在执行过程中遇到问题通知类A,这时候我们需要用到代理(Delegate)。
又比如:控制器(Controller)与控制器(Controller)之间的传值,从C1跳转到C2,再从C2返回到C1时需要通知C1更新UI或者是做其它的事情,这时候我们就用到了代理(Delegate)传值。
一、定义一套公用的接口(Public)
首先新建一个协议文件ProtocolDelegate:填上协议文件名及文件类型(选择Protocol)
ProtocolDelegate.h代码(协议不会生成.m文件):
#import @protocol ProtocolDelegate // 必须实现的方法
@required
- (void)error;
// 可选实现的方法
@optional
- (void)other;
- (void)other2;
- (void)other3;
@end
以上代码可以单独放在一个h文件中,也可以写在相关类的h文件中
在需要使用到协议的类,import它的头文件:
#import "ProtocolDelegate.h"
在Storyboard上,先搭好界面
新建ViewControllerB,把B界面的类设置为ViewControllerB。
ViewControllerB.h
#import <UIKit/UIKit.h>
// 新建一个协议,协议的名字一般是由“类名+Delegate”
@protocol ViewControllerBDelegate <NSObject>
// 代理传值方法
- (void)sendValue:(NSString *)value;
@end
@interface ViewControllerB : UIViewController
// 委托代理人,代理一般需使用弱引用(weak)
@property (weak, nonatomic) id<ViewControllerBDelegate> delegate;
@end
ViewControllerB.m
#import "ViewControllerB.h"
@interface ViewControllerB ()
@property (strong, nonatomic) IBOutlet UITextField *textField;//需要连线
@end
@implementation ViewControllerB
/*协议里的方法在定义协议时不需要实现,在需要实现协议方法的类中实现,在这个示例中,ViewControllerBDelegate定义在ViewControllerB中,但没有实现它,而在ViewController.m中实现了协议方法sendValue,当下面的方法监测到了需要实现协议方法时,便通知执行协议方法
*/
//需要连线
- (IBAction)backAction:(id)sender
{
if ([_delegate respondsToSelector:@selector(sendValue:)]) { // 如果协议响应了sendValue:方法
[_delegate sendValue:_textField.text]; // 通知执行协议方法
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
ViewController.m
#import "ViewController.h"
#import "ProtocolDelegate.h"
#import "ViewControllerB.h"
@interface ViewController () <ProtocolDelegate, ViewControllerBDelegate>
@end
@implementation ViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
ViewControllerB *vc = segue.destinationViewController;
[vc setDelegate:self];
}
// 这里实现B控制器的协议方法
- (void)sendValue:(NSString *)value
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:value delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
- (void)error
{
}
@end
小结:
当需要定义一套公用的接口,实现方法可以是不同的时候,可以使用Protocol协议。
当需要进行类与类之间的传值时,也可以基于Protocol协议,使用代理设计模式进行传值。
效果: