I have a very strange problem and I cannot find a solution. In one of my apps I need to create a UISearchDisplayController programatically. I am creating it in a subclass of UITableViewController. And I run into a very simple problem - my search display controller either gets released immediately OR it causes the retain cycle and prevents its contents controller from getting released.
In my viewDidLoad method I instantiate my UISearchDisplayController with this code:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
sC = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.delegate = self;
If sC is defined as a property or instance variable in my view controller, search controller works, but it prevents dealloc method of my view controller from being called. If, however, sC is defined as the variable only within viewDidLoad method, my view controller gets deallocated fine, but self.searchDisplayController becomes nil almost instantly and search doesn't work.
Does anyone know how to solve this? I have already tried overriding the searchDisplayController property - it doesn't help.
I should probably mention that I am using ARC. Also, when I say that "dealloc isn't called" I mean that I have an NSLog statement there which doesn't get printed.
Update
As some users suggested that there is already an answer and that simply overriding the searchDisplayController property should work I post below what I did (which didn't work).
I added a property to my subclass of UITableViewController:
@property (nonatomic,strong) UISearchDisplayController *searchDisplayController;
In my viewDidLoad I initialised my search controller:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.delegate = self;
In the dealloc method of my view controller I have:
- (void)dealloc
{
NSLog(@"dealloc");
self.searchDisplayController = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Line "dealloc" doesn't get printed and if I profile with instruments my view controller is not getting released.
I have also tried adding other properties with different name - it still doesn't get deallocated.