- 版權聲明:本文為博主原創(chuàng)文章朴皆,未經博主允許不得轉載缘薛。
前言:因為Object-C是不支持多繼承的,所以很多時候都是用Protocol(協(xié)議)來代替埃儿。Protocol(協(xié)議)只能定義公用的一套接口器仗,但不能提供具體的實現(xiàn)方法。也就是說蝌箍,它只告訴你要做什么青灼,但具體怎么做,它不關心妓盲。
當一個類要使用某一個Protocol(協(xié)議)時杂拨,都必須要遵守協(xié)議。比如有些必要實現(xiàn)的方法悯衬,你沒有去實現(xiàn)弹沽,那么編譯器就會報警告,來提醒你沒有遵守××協(xié)議筋粗。注意策橘,我這里說的是警告,而不是錯誤娜亿。對的丽已,就算你不實現(xiàn)那些“必要實現(xiàn)”的方法,程序也是能運行的买决,只不過多了些警告沛婴。
Protocol(協(xié)議)的作用:
一吼畏、定義一套公用的接口(Public)
@required:必須實現(xiàn)的方法
@optional:可選實現(xiàn)的方法(可以全部都不實現(xiàn))```
######二、委托代理(Delegate)傳值:
它本身是一個設計模式嘁灯,它的意思是委托別人去做某事泻蚊。
比如:兩個類之間的傳值,類A調用類B的方法丑婿,類B在執(zhí)行過程中遇到問題通知類A性雄,這時候我們需要用到代理(Delegate)。
又比如:控制器(Controller)與控制器(Controller)之間的傳值羹奉,從A1跳轉到A2秒旋,再從A2返回到A1時需要通知A1更新UI或者是做其它的事情,這時候我們就用到了代理(Delegate)傳值尘奏。
###一滩褥、定義一套公用的接口(Public)
//ProtocolDelegate.h代碼(協(xié)議不會生成.m文件):
import <Foundation/Foundation.h>
@protocol ProtocolDelegate <NSObject>
// 必須實現(xiàn)的方法
@required
- (void)error;
// 可選實現(xiàn)的方法
@optional
- (void)other;
- (void)other2;
- (void)other3;
@end```
在需要使用到協(xié)議的類,import它的頭文件:
#import "ViewController.h"
#import "ProtocolDelegate.h"```
我這里選擇的是入口文件
//記得要遵守協(xié)議:
@interface ViewController () <ProtocolDelegate>
@end
- 這時會報一個警告炫加,因為定義的協(xié)議里有一個是必須實現(xiàn)的方法瑰煎,而我們沒有去實現(xiàn):
```swift
實現(xiàn)了必須實現(xiàn)的方法后,編譯器就不會報警告了:
至于其它的可選方法俗孝,你可以選擇實現(xiàn)酒甸,也可以全都不實現(xiàn)。```
###二赋铝、委托代理(Delegate)傳值
//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];
}
// 這里實現(xiàn)B控制器的協(xié)議方法
(void)sendValue:(NSString *)value
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:value delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alertView show];
}(void)error
{
}
@end
//ViewControllerB.h文件:
import <UIKit/UIKit.h>
// 新建一個協(xié)議插勤,協(xié)議的名字一般是由“類名+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
- (IBAction)backAction:(id)sender
{
if ([_delegate respondsToSelector:@selector(sendValue:)]) { // 如果協(xié)議響應了sendValue:方法
[_delegate sendValue:_textField.text]; // 通知執(zhí)行協(xié)議方法
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
###小結:
``` swift
當你需要定義一套公用的接口革骨,實現(xiàn)方法可以是不同的時候农尖,你可以使用Protocol協(xié)議。
當你需要進行類與類之間的傳值時良哲,你也可以基于Protocol協(xié)議盛卡,使用代理設計模式進行傳值。