2015-10-08 38 views
4

我試圖在iOS 9中檢查我的示例應用程序的UIAlertController,並在運行它時發現了控制檯中的警告。我正在使用Xcode 7和Objective C.試圖在其視圖不在窗口層次結構中的UIViewController上呈現UIAlertController

請在控制檯中找到以下警告消息。

Warning: Attempt to present < UIAlertController: 0x7fb1bb5be040 > on < ViewController: 0x7fb1bb5aef30 > whose view is not in the window hierarchy!

請找到下面的代碼以獲取更多信息。

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert" 
                   message:@"This is an alert." 
                 preferredStyle:UIAlertControllerStyleAlert]; 

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault 
                 handler:^(UIAlertAction * action) {}]; 

[alert addAction:defaultAction]; 
[self presentViewController:alert animated:YES completion:nil]; 
+0

你在哪裏調用這段代碼? –

+0

你在viewDidload上調用了這個嗎? –

+0

@ Mr.T:是的,我打電話給viewDidLoad。 –

回答

13

我想,你正試圖提出警告視圖做負載。你得到的錯誤:

Warning: Attempt to present < UIAlertController: 0x7fb1bb5be040 > on < ViewController: 0x7fb1bb5aef30 > whose view is not in the window hierarchy!

因爲,在視圖中確實加載視圖尚不可顯示給用戶。因此你不能提出警報。將代碼移動到viewDidAppear

+3

這應該得到更多upvotes。使用'dispatch_async(dispatch_get_main_queue(),^ {...});'的普遍接受的解決方案是一種破解。 –

相關問題