iOS中协议的简单使用

什么是协议?

简单的理解:两个类之间,一个类委托另外一个类去实现某些方法或者功能;

实现1(DelegateViewController)

协议的关键字是@protocol
DelegateViewController.h

1
2
3
4
5
6
7
8
9
10
11
12
#import <UIKit/UIKit.h>
@protocol CoustomDelegate;//声明一个协议
@interface DelegateViewController : UIViewController
@property(nonatomic,weak)id<CoustomDelegate>delegate;//定义一个协议属性
@end
//协议方法
@protocol CoustomDelegate <NSObject>
//@required 默认方法是必须实现的,修饰词是@required,不实现的话,会报警告;
//@optional 修饰的方法不强制实现;
@optional
-(void)showMessage:(NSDictionary *)dic;
@end

DelegateViewController.m
在适当位置实现协议中的方法;

1
2
3
-(void)viewDidAppear:(BOOL)animated{
[self.delegate showMessage:@{@"key":@"value"}];
}

实现2(ViewController)

在ViewController.m 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import "ViewController.h"
#import "DelegateViewController.h"
@interface ViewController ()<CoustomDelegate>

@end
```
```
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
DelegateViewController * delegateVC = [[DelegateViewController alloc]init];
delegateVC.delegate = self;//实现委托,不要忘记;
[self presentViewController:delegateVC animated:YES completion:nil];
}
//协议方法
-(void)showMessage:(NSDictionary *)dic{
NSLog(@"delegate = %@",dic);
}

小结

协议是委托模式中的一种,协议也可以实现类之间值的传递;