UIViewController不会保留其通过编程方式创建的UISearchDisplayController。

30

在有关 searchDisplayController 属性的 UIViewController documentation1,它说:

如果您以编程方式创建搜索显示控制器,则在其初始化时,此属性会由搜索显示控制器自动设置。

当我这样创建我的 UISearchDisplayController 时:

[[[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self] autorelease];

-[UIViewController searchDisplayController] 不是 nil。但是,在事件循环完成后,它会被置为 nil,这导致当我点击搜索栏内部时,搜索显示控制器不会显示。没有任何崩溃。这非常奇怪。如果我省略对 autorelease 的调用,一切都正常:

[[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];

然而,发生了泄漏 UISearchDisplayController(我通过Instruments进行了验证)。由于searchDisplayController property被标记为(nonatomic, retain, readonly),我期望它在设置后会保留UISearchDisplayController

这篇stackoverflow文章与此有关。

2个回答

52

我也遇到了同样的问题。我通过编程方式创建所有的控制器/视图。一切都正常工作,直到我将项目转换为使用ARC。一旦我这么做了,UISearchDisplayControllers就不再被保留,每个UIViewController中的searchDisplayController属性在运行循环结束后变成了nil。

我不知道为什么会发生这种情况。苹果文档建议SDC应该由视图控制器保留,但显然并没有发生这种情况。

我的解决办法是创建第二个属性以保留SDC,在卸载视图时将其置为nil。如果您没有使用ARC,则需要在viewDidUnloaddealloc中释放mySearchDisplayController。否则,代码如下。

In MyViewController.h:

@property (nonatomic, strong) UISearchDisplayController * mySearchDisplayController;

在 MyViewController.m 文件中:

@synthesize mySearchDisplayController = _mySearchDisplayController;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // create searchBar
    _mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    _mySearchDisplayController.delegate = self;
    _mySearchDisplayController.searchResultsDataSource = self;
    _mySearchDisplayController.searchResultsDelegate = self;
    // other stuff
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    _mySearchDisplayController = nil;
    // other stuff
}

4
我尝试帮忙。就这件事,我没有看到任何官方文件。但显然我们俩都发现,这可能是故障或记录错误。 - XJones
1
我也遇到了ARC的这个问题。@XJones如果您能在此处发布openradar号码,那就太好了。与此同时,我想我会投票支持这个答案 :) - followben
3
两年后,您仍在帮助人们解决这个问题!非常感谢。我完全不知道为什么我的不起作用。 - Eric Amorde
1
同意。真不敢相信这个问题还没有解决。我刚刚浪费了一小时在这件事上。谢谢你确认我的理智。 - Jason McCreary
4
仍在iOS 7中。被骗了。 - an0
显示剩余6条评论

3

上面的解决方案很好用,但我也发现您可以使用

[self setValue:mySearchDisplayController forKey:@"searchDisplayController"]

UIViewController 子类的上下文中。

2
这可能有效,但不够稳定。Apple 未来的 SDK 可能会更改该键的名称。被接受的答案似乎是最好的。 - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接