大熊貓豬·侯佩原創或翻譯作品.歡迎轉載,轉載請注明出處.
如果覺得寫的不好請多提意見,如果覺得不錯請多多支持點贊.謝謝! 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>)
該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)}
可以看到在調用root VC注冊的selectionHandler閉包之后才做的dismissVC的操作,這顯然順序不對!
我們可以這樣修改:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {let selectedItem = items[indexPath]defer {selectionHandler?(selectedItem: selectedItem)}dismissViewControllerAnimated(true, completion: nil)}
好了!現在將selectionHandler的回調放到final中,即可保證在root VC中的操作是在dismissVC之后才開始的,這是root VC應該在window的繼承體系中了.