Delegate 是協議(@protocol)的一種應用方式。顧名思義,就是「委託他人幫自己做事」——當某件事自己做不方便處理時,就建立一個委託,把實作交給別人。
傳值:B 類要把自己的某個資料或物件交給 A 類去呈現或處理。這在兩個 View 之間傳遞參數時特別好用。
傳事件:A 類發生某件事後,通知關心它的委託對象,由對方決定該如何回應。也就是說 A 類本身不處理,而是透過 delegate 把事件轉交出去(委託對象 B 當然要先實作協議中的方法)。
一、需要定義 @protocol。它可以獨立成一個檔案,但慣例上是放在委託類別的標頭檔裡。
二、在協議中宣告委託對象需要代為處理的方法,用於傳值或傳事件。
三、委託類別中要宣告一個協議型別的實例,屬性通常設為 assign 而非 retain(以避免循環引用),命名慣例是 delegate;若類別本身已有同名屬性,就得換個名字。
四、被委託類別要在自己的 interface 中宣告 <XXXDelegate>,表示承諾實作該協議的方法。
五、最後務必把委託類別的 delegate 指向被委託對象,寫法有兩種:一是由外部設定 委託物件.delegate = 被委託物件;二是讓被委託類別內部持有委託物件,並設 delegate = self。
場景是 Customer 想買 iPhone,但銷售行為交給 Businessman 處理。Customer 是委託類別,Businessman 是被委託類別。
// Customer.h
#import <Foundation/Foundation.h>
@protocol MyDelegate <NSObject>
-(void)buyIphone:(NSString*)iphoneType;
@end
@interface Customer : NSObject
@property(nonatomic, assign) id<MyDelegate> delegate;
-(void)willBuy;
@end
// Customer.m
#import "Customer.h"
@implementation Customer
@synthesize delegate;
-(void)willBuy {
[delegate buyIphone:@"Iphone5"];
}
@end
// Businessman.h
#import <Foundation/Foundation.h>
#import "Customer.h"
@interface Businessman : NSObject <MyDelegate>
@end
// Businessman.m
#import "Businessman.h"
@implementation Businessman
-(void)buyIphone:(NSString *)iphoneType {
NSLog(@"There is an Iphone store, we have %@", iphoneType);
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Customer.h"
#import "Businessman.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Customer *customer = [[Customer alloc] init];
Businessman *businessman = [[Businessman alloc] init];
customer.delegate = businessman;
[customer willBuy];
}
return 0;
}
Boss 需要處理起草文件與接電話,但他本人不實作這些方法,而是交給秘書(Secretary)去做。
// Boss.h
#import <Foundation/Foundation.h>
@protocol MissionDelegate <NSObject>
-(void)draftDocuments;
-(void)tellPhone;
@end
@interface Boss : NSObject
@property(nonatomic, assign) id<MissionDelegate> delegate;
-(void)manage;
@end
// Boss.m
#import "Boss.h"
@implementation Boss
@synthesize delegate = _delegate;
-(void)manage {
[_delegate draftDocuments];
[_delegate tellPhone];
}
@end
// Secretary.h
#import <Foundation/Foundation.h>
#import "Boss.h"
@interface Secretary : NSObject <MissionDelegate>
@end
// Secretary.m
#import "Secretary.h"
@implementation Secretary
-(void)draftDocuments { NSLog(@"Secretary draft documents"); }
-(void)tellPhone { NSLog(@"Secretary tell phone"); }
@end
// main.m
Boss *boss = [[Boss alloc] init];
Secretary *secretary = [[Secretary alloc] init];
boss.delegate = secretary;
[boss manage];
自訂 MyView,內部放一個按鈕,但按鈕的事件不在自己處理,而是交給外部的委託對象——這在封裝可重複使用的自訂元件時非常常見。
// MyView.h
#import <UIKit/UIKit.h>
@protocol MyDelegate <NSObject>
-(void)print:(NSString*)viewName;
@end
@interface MyView : UIView
@property(nonatomic, assign) id<MyDelegate> mydelegate;
@end
// MyView.m
#import "MyView.h"
@implementation MyView
@synthesize mydelegate = _mydelegate;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button setFrame:CGRectMake(10, 10, 100, 50)];
[button setTintColor:[UIColor blueColor]];
// Target-Action 模式:事件交給自己,再由自己轉發給 delegate
[button addTarget:self action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
-(void)buttonPressed {
[_mydelegate print:@"this is a view"];
}
@end
// DelegateViewController.h
#import <UIKit/UIKit.h>
#import "MyView.h"
@interface DelegateViewController : UIViewController <MyDelegate>
@end
// DelegateViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
[myView setBackgroundColor:[UIColor yellowColor]];
myView.mydelegate = self;
[self.view addSubview:myView];
}
-(void)print:(NSString *)viewName {
NSLog(@"%@", viewName);
}
三個範例一路看下來,委託的骨架其實只有三塊:協議宣告方法、委託方持有 delegate 並在恰當時機呼叫、被委託方宣告協議並實作。理解這三塊,UIKit 裡大量的 delegate(UITableViewDelegate、UITextFieldDelegate 等)都能自行讀通了。