Search code examples
iosobjective-cuitableviewuisearchcontroller

Objective-c updateSearchResultsForSearchController not getting called


I am trying to apply a search feature to my UITableView. I added a search bar to the storeyboard scene like so:

enter image description here

then in my header file, I added the UISearchControllerDelegate and UISearchController like so:

@interface LHFileBrowser : UITableViewController UISearchControllerDelegate>

@property(nonatomic, retain) NSArray * tableData;
@property (strong, nonatomic) IBOutlet UINavigationBar *NavBar;
@property (strong, nonatomic) NSArray *results;
@property (strong, nonatomic) UISearchController *controller;

@end

and I added my updateSearchResultsForSearchController method to .m file

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {


    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains [c] %@", self.controller.searchBar.text];

    self.results = [self.tableData filteredArrayUsingPredicate:predicate];

}

and I put a break point at NSPredicate and when I try to use my search bar, I get nothing, it does not hit my break point so updateSearchResultsForSearchController is not being called. Is there something I am missing?


Solution

  • You need to set your TableViewController as the delegate for a number of things, so in viewDidLoad add:

    self.controller.searchResultsUpdater = self;
    self.controller.delegate = self;
    self.controller.searchBar.delegate = self;
    

    Also there's a typo in your interface, there should be a < before UISearchControllerDelegate.

    (As an aside, I'd recommend changing controller -> searchController to make your code less confusing.)