萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 父子 ViewController 通信模式:直接引用 vs 代理 vs Notification vs Responder Chain

場景

Container VC (Parent) 通過 addChildViewController: + [containerView addSubview:child.view] 嵌入 Child VC。雙向通信需求:Parent → Child 調用方法,Child → Parent 回調事件。

方案一:直接持有引用(最簡直接,耦合度高)

// Parent
@property (strong) ChildViewController *childVC;

- (void)embedChild {
    ChildViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildVC"];
    [self addChildViewController:child];
    [self.containerView addSubview:child.view];
    child.view.frame = self.containerView.bounds;
    [child didMoveToParentViewController:self];
    self.childVC = child;
}

// Parent → Child 直接調用
[self.childVC refreshData];

// Child → Parent:需 Parent 先傳遞 self
- (void)viewDidLoad {
    [super viewDidLoad];
    // 假設 Parent 在 embed 時調用
    // [self.childVC setParent:self]; // 見方案二
}

優點:簡單、編譯期檢查、無樣板代碼。
缺點:強耦合、難單測、Child 復用性差。

方案二:Child 持有弱引用 Parent(推薦輕量級)

// Child.h
@protocol ChildDelegate 
- (void)childDidRequestAction:(NSString *)action data:(id)data;
@end

@interface ChildViewController : UIViewController
@property (weak) id delegate; // 弱引用防循環
@end

// Parent.m
- (void)embedChild {
    ChildViewController *child = ...;
    child.delegate = self; // 設置代理
    ...
}

// Parent 實現協議
- (void)childDidRequestAction:(NSString *)action data:(id)data {
    if ([action isEqualToString:@"save"]) { ... }
}

// Child 觸發
[self.delegate childDidRequestAction:@"save" data:@{@"key": @"value"}];

優點:解耦、單向依賴、易測試、標準 Cocoa 模式。
注意:delegate 必須 weak,否則循環引用。

方案三:NotificationCenter 廣播(跨層級、多對多)

// Child 發送
[[NSNotificationCenter defaultCenter] postNotificationName:ChildDidFinishNotification
                                                    object:self
                                                  userInfo:@{@"result": data}];

// Parent 監聽
[[NSNotificationCenter defaultCenter] addObserverForName:ChildDidFinishNotification
                                                    object:self.childVC
                                                     queue:[NSOperationQueue mainQueue]
                                                usingBlock:^(NSNotification *note) {
    NSDictionary *info = note.userInfo;
    // 處理
}];

// dealloc 移除觀察者

優點:完全解耦、發送者無需知道接收者。
缺點:隱式流向、難追蹤、易過度使用導致混亂。

方案四:響應者鏈路傳遞(純 UIKit 風格)

// Child 中觸發
[[UIApplication sharedApplication] sendAction:@selector(handleChildAction:)
                                       to:nil
                                       from:self
                                     forEvent:nil];

// Parent 或任意響應者實現
- (void)handleChildAction:(id)sender {
    ChildViewController *child = (ChildViewController *)sender;
    // 處理
}

優點:無導入依賴、符合 UIKit 事件分發機制。
缺點:隱式、難調試、參數靈活性低。

選型決策樹

  • Parent 直接控制 Child 生命周期、Child 不復用 → 方案一
  • Child 可復用、需回調 Parent、雙方 1:1 → 方案二(代理/協議) ⭐ 推薦
  • 多個監聽者、跨模塊、非直接父子 → 方案三(通知)
  • 純 UI 事件、符合 Responder Chain 語義 → 方案四

現代 Swift 最佳實踐


// 協議 + 閉包回調(輕量、類型安全)
class ChildVC: UIViewController {
    var onAction: ((String, Any) -> Void)?
    
    @IBAction func saveTapped(_ sender: Any) {
        onAction?("save", ["key": "value"])
    }
}

// Parent
childVC.onAction = { [weak self] action, data in
    self?.handleAction(action, data: data)
}
copyright © 萬盛學電腦網 all rights reserved