這個範例涉及兩個類別與一個 delegate:A 類呼叫 B 類,B 類執行完畢後把一筆資料回傳給 A,A 再把它顯示出來。
一個標頭檔就足夠了:
#import <Foundation/Foundation.h> @protocol UIViewPassValueDelegate <NSObject> - (void)passValue:(NSString *)value; @end
任何實作了這個回呼方法的類別,就能取得傳入的 value。也就是說,接收資料的一方一定要實作這個回呼,本範例中就是 passValue:。
標頭檔:
#import <UIKit/UIKit.h>
#import "UIViewPassValueDelegate.h"
#import "ValueInputView.h"
@interface DelegateSampleViewController : UIViewController <UIViewPassValueDelegate> {
UITextField *_value;
}
@property (strong, nonatomic) IBOutlet UITextField *value;
- (IBAction)buttonClick:(id)sender;
@end
實作檔:
#import "DelegateSampleViewController.h"
@implementation DelegateSampleViewController
@synthesize value = _value;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidUnload {
[self setValue:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)buttonClick:(id)sender {
ValueInputView *valueView = [[ValueInputView alloc] init];
// 關鍵:把自己的 delegate 設為 B
valueView.delegate = self;
[self setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self presentModalViewController:valueView animated:YES];
}
// 實作協議方法,接收 B 傳回的值
- (void)passValue:(NSString *)value {
self.value.text = value;
NSLog(@"the get value is %@", value);
}
@end
標頭檔:
#import <UIKit/UIKit.h>
#import "UIViewPassValueDelegate.h"
@interface ValueInputView : UIViewController {
NSObject<UIViewPassValueDelegate> *delegate;
UITextField *_value;
}
@property (retain, nonatomic) IBOutlet UITextField *value;
@property (nonatomic, retain) NSObject<UIViewPassValueDelegate> *delegate;
- (IBAction)buttonClick:(id)sender;
@end
實作檔:
#import "ValueInputView.h"
@implementation ValueInputView
@synthesize value = _value;
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// 自訂初始化
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidUnload {
[self setValue:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)buttonClick:(id)sender {
[delegate passValue:self.value.text];
NSLog(@"self.value.text is %@", self.value.text);
[self dismissModalViewControllerAnimated:YES];
}
@end
第一,A 在 present B 之前必須先設定 valueView.delegate = self,這一步是整條資料通道的起點,少了它 B 的呼叫會直接落空(若 delegate 為 nil,Objective-C 傳訊給 nil 不會報錯,只會安靜地什麼都不做,因此這種 bug 特別難察覺)。
第二,示範中 delegate 宣告為 retain,在現代 ARC 環境下應改為 weak,否則 A 持有 B、B 又持有 A 會形成循環引用。這份程式碼風格屬於早期 MRC 時代的寫法,遷移到新專案時建議一併調整,並用 presentViewController:animated:completion: 取代已被棄用的 presentModalViewController。