一般來說,iOS 的畫面跳轉靠 pushViewController: 或 presentViewController: 就足夠,但前提是執行這行程式的 self 得是 view controller。如果跳轉邏輯寫在一個 NSObject 的子類別裡,該怎麼辦?
典型的情境是這樣的資料流:UICollectionView → NSObject 子類別 → UIViewController。
我們把 collection view 的 dataSource 與 delegate 都指向一個自訂的 NSObject 子類別,讓所有列表相關的邏輯集中管理。這種寫法讓 view controller 保持輕薄,很受歡迎。但當這個類別裡某個互動需要跳到另一個畫面時,就會卡住:
不能用 pushViewController:,因為 self 根本沒有 navigationController 屬性;
也不能用 presentViewController:,因為 self 不是 UIViewController 的子類別。
這是最符合 iOS 慣例的方式。在 NSObject 子類別中定義一個 delegate 協定,例如:
@protocol NYListLogicDelegate <NSObject>
- (void)listLogicDidRequestJump:(id)sender;
@end
@interface NYListLogic : NSObject <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, weak) id<NYListLogicDelegate> delegate;
@end
然後在需要跳轉的地方呼叫 delegate 方法:
[self.delegate listLogicDidRequestJump:self];
而這個方法的實作放在 view controller 裡——它本身就有 navigationController,於是正常的 push 或 present 都能用了。這個做法最大的好處是:邏輯類別完全不需要知道「跳去哪裡」,它只負責宣告「我現在需要跳轉」,決策權交回給 view controller。耦合度低,也更好測試。
如果不想多定義協定,也可以直接從 window 拿到目前的根控制器再跳:
UIViewController *rootViewController =
[[[UIApplication sharedApplication] keyWindow] rootViewController];
[rootViewController presentViewController:filterCourseViewController animated:NO completion:nil];
這個寫法短,但有兩個明顯缺點。第一,直接對 rootViewController 做 present,跳轉來源與堆疊關係容易變得混亂,特別是 root 是 UINavigationController 時,你繞過了 nav 的堆疊管理。第二,keyWindow 在多 window 場景(例如 iPad 分割畫面)下並不可靠,iOS 13 之後更應改用 UIScene 取得正確的 window。
歸根究柢,要執行 push 或 present,程式碼所在的 self 必須具備 navigationController 屬性,或本身就是 UIViewController 的子類別。因此實務上請優先採用 delegate(或 closure)回呼,把跳轉的決定權留在 view controller;只有在快速驗證的 Prototype 中,才適合直接用 rootViewController 硬跳。