以前有人问过这个问题,但我无法得到关于这个问题的明确解释。我有一个带有 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
此外,当我在搜索栏上键入内容时,搜索 Controller 没有正确设置动画,也没有调用 updateSearchResultsForSearchController
委托(delegate)。
但是,所有这些问题都可以通过对 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) 中创建变量,它的生命周期与函数生命周期相同。在这种情况下,您尝试将表头 View 设置为正在释放的 searchController(它的生命周期与 viewDidLoads 相同)
当您在 viewDidLoad 之外创建变量并稍后实例化它时,该变量与 viewController/class 具有相同的生命周期
关于ios - UISearchViewController 不允许在解除分配时尝试加载 View Controller 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36640648/