iOS 開發中 Whose view is not in the window hierarchy 錯誤的解決辦法

在 iOS 開發當中經常碰到 whose view is not in the window hierarchy 的錯誤,該錯誤簡單的說,是由於 "ViewController" 還沒有被加載,就調用該 ViewController 或者 ViewController 內的方法時,就會報這個錯誤。
 
在不同地方調用 ViewController,解決的方法也不太一樣。
 
1. 在 一個 ViewController 裏面調用另外一個 ViewController 是出現這個錯誤: 

該錯誤一般是由於在 viewDidLoad 裏面調用引起的,解決辦法是轉移到 viewDidAppear 方法裏面
 
2. 在 AppDelegate.m 中調用遇到這個錯誤 
 
解決辦法1:
 
UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topRootViewController.presentedViewController)
 {
    topRootViewController = topRootViewController.presentedViewController;
 }
 
//[topRootViewController presentViewController:yourController animated:YES completion:nil];
//or
[topRootViewController myMethod];
 
解決辦法2:
 
 UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginViewController* loginViewController = [mainstoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [self.window makeKeyAndVisible];
//[LoginViewController presentViewController:yourController animated:YES completion:nil];
//or
[LoginViewController myMethod];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章