簡體   English   中英

UISearchViewController不允許在取消分配時嘗試加載視圖控制器的視圖

[英]Attempting to load the view of a view controller while it is deallocating is not allowed for UISearchViewController

之前已經問過這個問題,但是我無法對這個問題做出明確的解釋。 我有一個簡單的應用程序,具有tableview和搜索功能。 viewDidLoad() ,我調用setUpSearchView() ,它定義如下

  let searchController = UISearchController(searchResultsController: nil)
  searchController.searchResultsUpdater = self
  searchController.hidesNavigationBarDuringPresentation = true
  searchController.dimsBackgroundDuringPresentation = false
  self.tableView.tableHeaderView = searchController.searchBar

此代碼無法正常工作。 在控制台上,我可以看到此錯誤

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior

此外,searchcontroller沒有正確設置動畫,並且當我在搜索欄上鍵入時不會調用updateSearchResultsForSearchController委托。

但是,通過對searchController初始化函數進行微小更改,可以輕松解決所有這些問題。 而不是將searchController聲明為searchController中的局部變量,如果我在方法之外聲明它是一個實例變量,就像這個var searchController:UISearchController! 一切正常,雖然我不知道為什么。

現在代碼看起來像這樣

var searchController:UISearchController!

在setUpSearchView()中

 searchController = UISearchController(searchResultsController: nil)
 searchController.searchResultsUpdater = self
 searchController.hidesNavigationBarDuringPresentation = true
 searchController.dimsBackgroundDuringPresentation = false
 self.tableView.tableHeaderView = searchController.searchBar

這是github上viewController的鏈接: https//github.com/tmsbn/marvel_heroes/blob/master/avengers/HeroesListController.swift

有人可以解釋為什么會這樣嗎? 這是swift的錯誤嗎? 或者它是iOS中我不了解的東西。

如果要在函數(viewDidLoad)中創建變量,則其生命周期與函數生存期相同。 在這種情況下,您嘗試將表頭視圖設置為正在釋放的searchController(它的生命周期與viewDidLoads相同)

在viewDidLoad之外創建變量並稍后實例化時,該變量與viewController / class具有相同的生命周期

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM