您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 頁面跳轉與資料傳遞的常見做法

編輯:iOS 相關資訊

頁面(ViewController)之間的跳轉與資料傳遞,是每個 iOS 應用都會遇到的基礎課題。以下整理幾種常見的跳轉方式與資料回傳策略。

一、頁面跳轉的三種方式

1. 透過 UINavigationController 堆疊

// 進入子頁面
[self.navigationController pushViewController:subTableViewController animated:YES];
// 返回上一頁
[self.navigationController popViewControllerAnimated:YES];

2. 模態(Modal)呈現

UIViewController *control = [[UIViewController alloc] init];
[self presentModalViewController:control animated:YES];
[control release];
// 關閉模態
[self dismissModalViewControllerAnimated:YES];

3. 直接切換 view

[self.view.window addSubview:otherview];
[self.view removeFromSuperview];

二、資料傳遞的常見策略

  1. 代理(Delegate)模式:子 view controller 定義協定,父 view controller 實作該協定;子頁面退出時透過 delegate 把資料回傳並更新父頁面。這是最推薦、最夠物件導向的做法。
  2. 通知(NSNotificationCenter)機制:父頁面註冊訊息,子頁面發送訊息觸發父頁面的處理。
    // 註冊監聽
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(setData:)
                                                 name:kNotificationMessage
                                               object:nil];
    // 發送訊息
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMessage
                                                        object:self
                                                      userInfo:infoDict];
    
  3. 以資料庫作為中介:子頁面把狀態存入 DB,父頁面再從 DB 讀取並更新 view,適合較大量或需持久化的資料。
  4. 使用 NSUserDefaults:適合儲存少量、輕量的設定型資料。
  5. 透過 AppDelegate 的全域變數:把 AppDelegate 當作中介保存共用資料,簡單直接但耦合度較高。

選擇哪一種,取決於資料量、生命週期與團隊的架構慣例。一般來說,delegate 適合回傳結果、通知適合跨多層廣播、DB 與 NSUserDefaults 則負責持久化。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved