今天遇到一個不算罕見但頗惱人的問題,記錄下來,希望其他人搜尋時能少繞幾圈。
這個 App 需要登入後才能使用,因此我用替換 [UIApplication sharedApplication].keyWindow.rootViewController 的方式來控制登入與登出後的畫面切換。操作流程是:
1. 登入成功後,點擊「登出」按鈕,跳出確認用的 UIAlertView;
2. 確認登出後重新回到登入畫面;
3. 再次登入並點擊「登出」——這次 UIAlertView 不再跳出來了。
主控台出現的警告是:
attempt to dismiss modal view controller whose view does not currently appear
而第二次點擊登出時,訊息變成:
Attempt to present <_UIModalItemsPresentingViewController> on
<_UIModalItemAppViewController> whose view is not in the window hierarchy!
LoginViewController *loginVC = [[LoginViewController alloc] init];
CNavigationController *nav = [[CNavigationController alloc] initWithRootViewController:loginVC];
[UIApplication sharedApplication].keyWindow.rootViewController = nav;
這段程式碼是寫在 - (void)alertView:clickedButtonAtIndex: 這個 delegate 方法裡的。也就是說,在我把 rootViewController 換掉的當下,UIAlertView 的關閉動畫還沒結束。它仍然掛在原本的 window 上,而 window 的 rootViewController 卻已經被換掉,於是 UIKit 就拋出了「你想關掉一個 view 尚未出現的 modal」這種訊息。更麻煩的是,這個狀態會殘留,導致後續的呈現動作也跟著失敗。
把切換 rootViewController 的動作,從 clickedButtonAtIndex: 移到另一個 delegate 方法:
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == alertView.cancelButtonIndex) {
return;
}
// 這裡只做狀態處理,不做 view 切換
}
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == alertView.cancelButtonIndex) {
return;
}
// alert 徹底消失後才切換根控制器
LoginViewController *loginVC = [[LoginViewController alloc] init];
CNavigationController *nav =
[[CNavigationController alloc] initWithRootViewController:loginVC];
[UIApplication sharedApplication].keyWindow.rootViewController = nav;
}
didDismissWithButtonIndex: 是在 alert 完全消失之後才呼叫,這時再換 rootViewController 就不會衝突了。
1. UIAlertView 在 iOS 8 之後已被標記為 deprecated,新專案請改用 UIAlertController,並在它的 completion block 中處理後續動作,就不會有這個時序問題。
2. 用「直接替換 rootViewController」來做登入狀態切換,本身就容易衍生各種時序與動畫衝突。更穩健的做法是在 App 啟動時就設定好根控制器,登入/登出時改用 modal 呈現或 transitionFromViewController: 來切換,讓 UIKit 幫你管理狀態。