【问题标题】:Attempting to load the view of a view controller while it is deallocating is not allowed for UISearchViewControllerUISearchViewController 不允许在解除分配时尝试加载视图控制器的视图
【发布时间】:2016-04-15 07:18:43
【问题描述】:

以前有人问过这个问题,但我无法清楚地解释这个问题。我有一个带有表格视图和搜索功能的简单应用程序。在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 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 中我不知道的东西。

【问题讨论】:

标签: ios swift uisearchcontroller


【解决方案1】:

如果您在函数 (viewDidLoad) 中创建变量,它的生命周期与该函数的生命周期相同。在这种情况下,您尝试将表头视图设置为正在释放的 searchController(它的生命周期与 viewDidLoads 相同)

当您在 viewDidLoad 之外创建变量并稍后实例化它时,该变量与 viewController/class 具有相同的生命周期

【讨论】:

  • 对不起,我不太明白。为什么 searchController 在被设置为表头视图之前被释放?设置表头视图是否为异步函数。
  • 我认为在运行代码时,编译器会看到该变量将在 viewDidLoad 结束时被释放,因此将其设置为表头会标记该错误。这是因为现在设置表头时,指向该对象的所有指针都消失了,这就是委托方法不起作用的原因等等。
  • 我明白了.. 这是有道理的。谢谢你的解释!
  • 没问题!很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多