前言:由於Object-C是不支持多繼承的,因此不少時候都是用Protocol(協議)來代替。Protocol(協議)只能定義公用的一套接口,但不能提供具體的實現方法。也就是說,它只告訴你要作什麼,但具體怎麼作,它不關心。設計模式
當一個類要使用某一個Protocol(協議)時,都必需要遵照協議。好比有些必要實現的方法,你沒有去實現,那麼編譯器就會報警告,來提醒你沒有遵照××協議。注意,我這裏說的是警告,而不是錯誤。對的,就算你不實現那些「必要實現」的方法,程序也是能運行的,只不過多了些警告。工具
我會在本文的結尾放上此Demo的下載地址,有須要的話能夠去下載,謝謝。開發工具
Protocol(協議)的做用:測試
1、定義一套公用的接口(Public)網站
@required:必須實現的方法,默認在@protocol裏的方法都要求實現。ui
@optional:可選實現的方法(能夠所有都不實現)atom
2、委託代理(Delegate)傳值:spa
它自己是一個設計模式,它的意思是委託別人去作某事。
設計
好比:兩個類之間的傳值,類A調用類B的方法,類B在執行過程當中遇到問題通知類A,這時候咱們須要用到代理(Delegate)。3d
又好比:控制器(Controller)與控制器(Controller)之間的傳值,從C1跳轉到C2,再從C2返回到C1時須要通知C1更新UI或者是作其它的事情,這時候咱們就用到了代理(Delegate)傳值。
1、定義一套公用的接口(Public)
首先新建一個協議文件:
填上協議文件名及文件類型(選擇Protocol):
ProtocolDelegate.h代碼(協議不會生成.m文件):
#import <Foundation/Foundation.h> @protocol ProtocolDelegate <NSObject> // 必須實現的方法 @required - (void)error; // 可選實現的方法 @optional - (void)other; - (void)other2; - (void)other3; @end
在須要使用到協議的類,import它的頭文件:
#import "ViewController.h" #import "ProtocolDelegate.h"
我這裏選擇的是入口文件
記得要遵照協議:
@interface ViewController () <ProtocolDelegate>
@end
這時會報一個警告,由於定義的協議裏有一個是必須實現的方法,而咱們沒有去實現:
實現了必須實現的方法後,編譯器就不會報警告了:
至於其它的可選方法,你能夠選擇實現,也能夠全都不實現。
2、委託代理(Delegate)傳值
在Storyboard上,先搭好界面,以下圖:
新建ControllerB:
把B界面的類設置爲ViewControllerB:
下面放出主要類文件代碼,我在裏面寫了註釋,你們應該能看懂。不懂也沒有關係,我會在本文結尾放上Demo下載地址。
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
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 - (IBAction)backAction:(id)sender { if ([_delegate respondsToSelector:@selector(sendValue:)]) { // 若是協議響應了sendValue:方法 [_delegate sendValue:_textField.text]; // 通知執行協議方法 } [self.navigationController popViewControllerAnimated:YES]; } @end
完成效果截圖:
小結:
當你須要定義一套公用的接口,實現方法能夠是不一樣的時候,你可使用Protocol協議。
當你須要進行類與類之間的傳值時,你也能夠基於Protocol協議,使用代理設計模式進行傳值。
Demo測試經過環境:
開發工具:Xcode6.1 測試機型:模擬器 測試系統:IOS8.0
Demo下載地址:GCProtocol&Delegate
在百度看搜索了下本文,發現有些轉載網站的連接給弄沒了,所以這裏添加一個:
Demo下載地址::http://pan.baidu.com/s/1ntJYgvJ
博文做者:GarveyCalvin
博文出處:http://www.cnblogs.com/GarveyCalvin/
本文版權歸做者和博客園共有,歡迎轉載,但須保留此段聲明,並給出原文連接,謝謝合做!