Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchDisplayDelegate method not called

I programmatically create a UISearchBar and UISearchDisplayController. The view controller is a UITableViewController. @interface StockTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate> You can see the code below. But when I type in the search bar, shouldReloadTableForSearchString not get called including other UISearchDisplayDelegate methods.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchResults = [NSArray array];

    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.barStyle = UISearchBarStyleDefault;
    searchBar.searchBarStyle = UISearchBarStyleDefault;
    searchBar.showsCancelButton = YES;
    searchBar.showsScopeBar = NO;
    searchBar.delegate = self;

    UISearchDisplayController *searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;

    self.tableView.tableHeaderView = searchBar;
}

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    NSLog(@"searching"); //not showed up in the console
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@"%@", searchString); //not showed up in the console
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE %@", searchString];
    NSArray *results = [Stock MR_findAllSortedBy:@"createdDate" ascending:NO withPredicate:predicate];
    if ([results count] > 0) {

        self.searchResults = results;
        [self.searchDisplayController.searchResultsTableView reloadData];
    }
    return YES;
}
like image 570
yong ho Avatar asked Jan 21 '26 15:01

yong ho


1 Answers

It doesn't work because you're creating your UISearchDisplayController as a local variable, which causes it to be deallocated when viewDidLoad goes out of scope. So create a strong property for your search display controller, and then it should work properly (you'll run into a naming conflict if you name the property, searchDisplayController, so call it something else).

like image 146
rdelmar Avatar answered Jan 24 '26 06:01

rdelmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!