委托其實並不是OC中才有,C#中也有,不過彼此的理解方式是不一樣的,OC中委托是協議的一種,需要使用@protocol聲明,委托一般在iOS開發中頁面中傳值用的比較多。委托是Cocoa中最簡單、最靈活的模式之一,委托其實字面上的意思就是將需要的事情委托給別人做,業務場景可以參考主視圖和子視圖之間的頁面關系,或者是視圖層和數據層之間的交互。
簡單的委托
委托通過@protocol聲明,可以定義方法,引用委托的對象,需要實現其方法,方法默認都是@required的,同時可以設置為可選的@optional,首先定義個委托:
@protocol BookDelegate <NSObject> @required - (void)getBookCount; @optional - (void)optionMethod; @end
這個時候定義書籍Book類和客戶Customer類:
@interface Book : NSObject<BookDelegate> @end @interface Customer : NSObject<BookDelegate> @property (assign,nonatomic) id<BookDelegate> didBookDelegate; @end
實現其中的getBookCount方法:
@implementation Book - (void)getBookCount{ NSLog(@"Book中getBookCount的實現"); } @end @implementation Customer - (void)getBookCount{ NSLog(@"Customer中getBookCount的實現"); } @end
簡單的調用:
Book *book=[[Book alloc]init]; Customer *customer=[[Customer alloc]init]; [customer getBookCount]; [book getBookCount];
上面幾行的代碼的結果,不用說大家也能看的懂,接下來看接下來的代碼,這個時候大家發現用到了開始頂一個的didBookDelegate:
customer.didBookDelegate=book; [customer.didBookDelegate getBookCount];
上面就是將Book的實例,Book實現了BookDelegate,這個時候可將Book的實例賦值給customer中的變量,將自己的實例化對象委托給了didBookDelegate。
以上是委托使用基本的場景,作為實例化對象book可以自己執行其方法,也可以通過委托將執行過程轉移。
頁面傳值
簡單的就是A頁面數據可以傳值給B頁面,B頁面可以傳值給A頁面,簡單的兩個頁面傳值,頁面參考如下:
都是文本框和按鈕,跳轉方式選取的時Modal:
第一個頁面ViewController的定義:
#import <UIKit/UIKit.h> #import "SecondViewController.h" @interface ViewController : UIViewController<StudySubjectDelegate> @property (strong, nonatomic) IBOutlet NSString *firstData; @property (weak, nonatomic) IBOutlet UITextField *subjectName; @end
第二個頁面SecondViewController頭文件的定義,並且聲明了一個委托:
// // SecondViewController.h // Sample // // Created by keso on 15/2/3. // Copyright (c) 2015年 keso. All rights reserved. // #import <UIKit/UIKit.h> @class SecondViewController; @protocol StudySubjectDelegate <NSObject> - (void)shouldChangeValue:(SecondViewController*)controller; @end @interface SecondViewController : UIViewController @property (assign,nonatomic) id<StudySubjectDelegate> firstViewDelegate; @property (weak, nonatomic) IBOutlet NSString *showData; @property (weak, nonatomic) IBOutlet UITextField *studySubject; @end
ViewController.m中的點擊事件:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:@"firstEdit"]) { SecondViewController *controller=segue.destinationViewController; NSLog(@"%@",self.subjectName.text); //將自己本身的實例傳遞給第二個視圖 controller.firstViewDelegate=self; controller.showData=self.subjectName.text; } }
賦值的方式還可以是這樣的,其實中的key就是第二個視圖定義的屬性:
if ([controller respondsToSelector:@selector(setShowData:)]) { [controller setValue:self.subjectName.text forKey:@"showData"]; }
第二個頁面的點擊事件就比較簡單了,代碼如下:
[self.firstViewDelegate shouldChangeValue:self];
上面中其實可以簡單的看到oc中的委托就是將自己的實例交給其他對象的成員變量,然后由其成員變量執行實例的工作,的今天不知道為什么有點頭疼,說個事情就是最后的第二個頁面跳轉到一個頁面可以接收到值,無法給UITextField賦值,暫時沒有搞明白如何才能賦值上去,每次進入就變成了null,有知道可以指點一下,多謝~