首頁 → 通訊介面(含 Switch 開關),按返回鍵回首頁,再次進入通訊介面時希望保持原有 UIView 實例與狀態(Switch 狀態、連線資訊),而非重新初始化。
使用 UINavigationController 推疊時,不要每次都 new 新實例,而是持有強引用複用。
// RootViewController.h
@property (nonatomic, strong) CommunicationViewController *commVC;
// RootViewController.m
- (void)gotoCommunication {
if (!self.commVC) {
self.commVC = [[CommunicationViewController alloc] init]; // 首次建立
}
[self.navigationController pushViewController:self.commVC animated:YES];
}
pushViewController: 只負責將既有 VC 推入導航堆疊,不會觸發 viewDidLoad(僅觸發 viewWillAppear/viewDidAppear)。popViewControllerAnimated:,只會移除視圖層級,不會釋放 VC 實例(除非記憶體警告觸發 didReceiveMemoryWarning 釋放可重建資源)。instantiateViewController 產生新實例。instantiateViewControllerWithIdentifier: 並持有引用,或實作 prepareForSegue: 檢查是否已存在實例並手動指派。將通訊邏輯(Socket、狀態機)封裝在獨立的 CommunicationManager 單例或 Service 層,VC 僅負責 UI 綁定。如此即使 VC 被釋放重建,核心狀態仍在 Manager 中保持,解耦更徹底。