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.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,否則循環引用。
// 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 移除觀察者
優點:完全解耦、發送者無需知道接收者。
缺點:隱式流向、難追蹤、易過度使用導致混亂。
// Child 中觸發
[[UIApplication sharedApplication] sendAction:@selector(handleChildAction:)
to:nil
from:self
forEvent:nil];
// Parent 或任意響應者實現
- (void)handleChildAction:(id)sender {
ChildViewController *child = (ChildViewController *)sender;
// 處理
}
優點:無導入依賴、符合 UIKit 事件分發機制。
缺點:隱式、難調試、參數靈活性低。
// 協議 + 閉包回調(輕量、類型安全)
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)
}