控制器之間傳值是 iOS 面試與日常工作裡的必備技能。本文以「控制器 A」與「控制器 B」為例,把順傳與逆傳兩個方向一次講透,並附上一個可直接運行的完整範例。

下面用一個雙向傳值的 demo 把兩種手法串起來:A 的輸入框打字後跳到 B,B 會顯示這段文字;在 B 修改後返回,A 的下方輸入框會同步更新。
#import <UIKit/UIKit.h> @interface FirstViewController : UIViewController @end
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController () <SecondViewControllerDelegate>
/** 用於寫入資料,最後傳給第二個介面 */
@property (weak, nonatomic) IBOutlet UITextField *first2Second;
/** 用於顯示第二個介面回傳的資料 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithSecond;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - Navigation
// 點擊傳遞按鈕時會自動呼叫此方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SecondViewController *vc = (SecondViewController *)segue.destinationViewController;
// 順傳:把本頁的資料交給目標控制器
if (self.first2Second.text.length > 0) {
vc.name = self.first2Second.text;
}
// 同時把自己設為 B 的代理,準備接收逆傳資料
vc.delegate = self;
}
#pragma mark - 實作 SecondViewControllerDelegate
- (void)secondViewControllerDidDit:(SecondViewController *)viewController
andName:(NSString *)name {
// 逆傳:接收第二個介面回傳的資料並顯示
self.displayWithSecond.text = name;
}
@end
這裡是逆傳的核心:先用 @class 前向宣告避開循環引用,再定義協定。
#import <UIKit/UIKit.h>
@class SecondViewController;
@protocol SecondViewControllerDelegate <NSObject>
/** SecondViewControllerDelegate 協定中的方法 */
- (void)secondViewControllerDidDit:(SecondViewController *)viewController
andName:(NSString *)name;
@end
@interface SecondViewController : UIViewController
@property (nonatomic, strong) NSString *name;
@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate;
@end
#import "SecondViewController.h"
@interface SecondViewController ()
/** 用於寫入資料,最後回傳給第一個介面 */
@property (weak, nonatomic) IBOutlet UITextField *second2First;
/** 用於顯示第一個介面傳來的資料 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithFirst;
/** 點擊此按鈕會讓本控制器出棧,介面返回上一頁 */
- (IBAction)second2First:(UIButton *)sender;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 顯示第一個介面傳過來的資料
self.displayWithFirst.text = self.name;
}
- (IBAction)second2First:(UIButton *)sender {
if (self.second2First.text.length > 0) {
// 只有當對方實作了該協議方法時才回呼,避免 crash
if ([self.delegate respondsToSelector:@selector(secondViewControllerDidDit:andName:)]) {
[self.delegate secondViewControllerDidDit:self andName:self.second2First.text];
}
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
第一,prepareForSegue:sender: 是 storyboard 場景下做順傳最省事的位置,跳轉發生前就會被呼叫,此時同時完成「賦值」與「設定 delegate」剛剛好。
第二,逆傳前務必用 respondsToSelector: 做保護。若 delegate 為 nil 或未實作該方法,直接呼叫會造成崩潰。
第三,delegate 屬性一定要宣告為 weak,否則 A 持有 B、B 又持有 A,會形成循環引用導致記憶體洩漏。
如果頁面層級較深、需要跨越多層回傳,則可以改用通知(NSNotificationCenter)或 block 回呼,它們在解耦上比 delegate 更進一步,代價是資料流向變得較不直觀。可依專案規模自行取捨。