【问题标题】:Unavoidable retain cycle using UISearchBar as UITableView's header view?使用 UISearchBar 作为 UITableView 的标题视图不可避免的保留周期?
【发布时间】:2016-09-22 00:22:30
【问题描述】:

我在构建使用UISearchController 的基本用户界面时遇到了这个问题,它是UISearchBar 成员。我的 tableView 是一个弱 IBOutlet,就像 Apple Docs 演示的那样,我将它的 tableHeaderView 属性设置为搜索栏成员。

//Snippet from viewDidLoad
UISearchController* searchController = [self createSearchController];
UISearchBar* searchBar = searchController.searchBar;
searchBar.userInteractionEnabled = NO;

self.tableView.tableHeaderView = searchBar; //The assignment in question

[NetworkStuff makeCall:^(Response *response) {
    //handle success
    searchBar.userInteractionEnabled = YES; //local variables
    searchController.active = YES;
    ...
} failure:^(Response *response) {
    //handle failure
    ...
}];

当我从堆栈中弹出视图时,它的 dealloc 方法永远不会被调用,即使我在viewWillDisappear: 中将 tableHeaderView 设置为 nil。我需要注释掉才能看到调用 dealloc 的唯一行是初始分配。

有人知道为什么会发生这种情况吗?

编辑:

发现了一些有趣的行为。同样根据 Apple Docs,我将控制器的 definesPresentationContext 变量设置为 YES。在将 tableViewHeader 分配保留在固定保留周期中时将其注释掉,即使我没有取消 tableViewHeader。但是,在viewDidLoad 中设置definesPresentationContext 并在viewWillDisappear 中清除它会重新引入保留周期。

【问题讨论】:

    标签: ios objective-c uitableview automatic-ref-counting uisearchbar


    【解决方案1】:

    偶然发现了这个答案: UISearchController retain issue

    解决方案似乎是在viewDidDisappear: 中显式关闭 UISearchController(请注意,我无法让它在viewWillDisappear: 中工作)。由于该代码很快,我将在此处将其转录为 Objective-C:

    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    
        if (!self.presentingViewController) {
            [self.searchController dismissViewControllerAnimated:NO completion:nil];
        }
    }
    

    正如原始答案指出的那样,在另一个视图控制器被推到视图顶部的情况下,检查self.presentingViewController 的不存在是有帮助的,因为我们会回到页面。很可能,我们只想在弹出包含它的视图控制器时关闭 searchController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多