30

在关于属性1的UIViewController 文档中,它说:searchDisplayController

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

当我这样创建我的 UISearchDisplayController 时:

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

-[UIViewController searchDisplayController]不是nil。但是,它在事件循环完成后被取消,这导致当我在搜索栏内触摸时搜索显示控制器不显示。没有什么崩溃。这很奇怪。如果我省略对 的调用autorelease,一切正常:

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

但是,泄漏了UISearchDisplayController(我用 Instruments 验证了这一点)。由于该searchDisplayController 属性被标记为(nonatomic, retain, readonly)我期望它UISearchDisplayController在设置后会保留。

这篇stackoverflow文章是相关的。

4

2 回答 2

53

我遇到了同样的事情。我以编程方式创建所有控制器/视图。在我将项目转换为使用 ARC 之前,一切正常。一旦我这样做了UISearchDisplayControllers,就不再保留,并且在运行循环结束后searchDisplayController每个属性都为零。UIViewController

我不知道为什么会这样。Apple 文档建议视图控制器应保留 SDC,但这显然不会发生。

我的解决方案是创建第二个属性来保留 SDC,并在卸载视图时将其设为 nil。如果您不使用 ARC,则需要mySearchDisplayControllerviewDidUnloaddealloc. 否则这很好。

在 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
}
于 2011-10-31T18:28:21.517 回答
3

上面的解决方案工作得很好,但我也发现你可以使用

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

UIViewController子类的上下文中。

于 2012-03-28T21:33:17.620 回答