1. 程式人生 > >iOS開發出錯whose view is not in the window hierarchy 的解決

iOS開發出錯whose view is not in the window hierarchy 的解決

                     
 

大熊貓豬·侯佩原創或翻譯作品.歡迎轉載,轉載請註明出處.   如果覺得寫的不好請多提意見,如果覺得不錯請多多支援點贊.謝謝! hopy ;)

一個簡單的單視窗App在執行時出現錯誤:

2016-04-07 14:28:48.411 BlurViewAndPopView[4364:168520] Warning: Attempt to present <UIAlertController: 0x7a0a4e00> on <BlurViewAndPopView.ViewController: 0x797757d0> whose view is not in the window hierarchy!2016
-04-07 14:28:48.935 BlurViewAndPopView[4364:168520] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x7a0a4e00>)
  • 1
  • 2
  • 3

該app的功能是在root VC中彈出一個popover檢視,其中包含一個表檢視,在點選表檢視中的某一行時回撥root VC中的閉包,完成改行內容的對話方塊彈出效果.

分析如下:根據錯誤資訊,可以清楚看到在試圖彈出對話方塊時,root VC不在視窗的繼承體系中,這意味著此時root VC不在window中.

檢視popover的cellSelect回撥方法:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        let selectedItem = items[indexPath]        selectionHandler?(selectedItem: selectedItem)        dismissViewControllerAnimated(true, completion: nil)    }
  • 1
  • 2
  • 3
  • 4
  • 5

可以看到在呼叫root VC註冊的selectionHandler閉包之後才做的dismissVC的操作,這顯然順序不對!

我們可以這樣修改:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        let selectedItem = items[indexPath]        defer {            selectionHandler?(selectedItem: selectedItem)        }        dismissViewControllerAnimated(true, completion: nil)    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

好了!現在將selectionHandler的回撥放到final中,即可保證在root VC中的操作是在dismissVC之後才開始的,這是root VC應該在window的繼承體系中了.