Search code examples
iosxcodeuisearchdisplaycontroller

Objective-C/Xcode 6: Best way to have a Search Bar populate a table view?


I have table view with a Search Bar above it. My intention is to have users enter a query in the search bar and have the table view populate with results - either when the user presses enter or as they're typing.

After reading a number of tutorials, I selected the Search Bar and Search Display Controller for the Search Bar. However, it seems this controller is less of an enter-query-then-display-results tool than a filter-existing-table-view-data tool. This means I'm coming upon a table view that already has all the data and is filtered as I type -- what I'd like is to come upon an empty table view and have it populate.

I was wondering if there was a way to use the Search Bar and Search Display Controller to achieve the effect I want or it there was a preferred way?


Solution

  • When using UISearchDisplayController you'll have two UITableViews. The one in your search view controller. So assuming you are hooking up both UITableView's dataSources to your UIViewController, just check which table is being passed in and return nothing if it's not for the search.

    For example

    - (NSArray *) _sectionArrayForTable:(UITableView *) tableView {
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            // Return your search results
        }
    
        // Show nothing when not searching
        return 0;
    }