How To Add Search Bar in Table View

One common questions I got about UITableView is how to implement a search bar for data searching. This tutorial will show how to add a search bar to the Tab Bar project. With the search bar, the app lets users search through the recipe list by specifying a search term.

Well, it’s not difficult to add a search bar but it takes a little bit of extra work. We’ll continue to work on the Xcode project we developed in the previous tutorial. If you haven’t gone through the tutorial, take some time to check it out or you can download the project here.

iOS App Search Bar

Understanding Search Display Controller

You can use search display controller (i.e. UISearchDisplayController class) to manage search in your app. A search display controller manages display of a search bar and a table view that displays the results of a search of data.

When a user starts a search, the search display controller will superimpose the search interface over the original view and display the search results. Interestingly, the results are displayed in a table view that’s created by the search display controller.

Search Results Table View vs Table View

Search Results Table View vs Table View

Like other view controllers, you can either programmatically create the search display controller or simply add it into your app using Storyboard. In this tutorial, we’ll use the later approach.

Adding a Search Display Controller in Storyboard

In Storyboard, drag and add the “Search Bar and Search Display Controller” right below the navigation bar of Recipe Book View Controller. If you’ve done correctly, you should have a screen similar to the below:

Adding Search Display Controller

Adding Search Display Controller

Before proceeding, try to run the app and see how it looks. Without implementing any new code, you already have a search bar. Tapping the search bar will bring you to the search interface. Yet, the search won’t give you the correct search result.

Search Bar in Table View App

Search Bar in Table View App But Not Working Yet

We Did Nothing but Why Search Results Show All Recipes?

As mentioned earlier, the search results are displayed in a table view created by the search display controller. When developing the table view app, we implement the UITableViewDataSource protocol to tell Table View how many rows to display and the data in each row.

Like UITableView, the table view created by the search display controller adopts the same approach. By referring to the official documentation of UISearchDisplayController, here are the available delegates that let you interact with the search result and search bar:

The search results table view’s data source.
This object is responsible for providing the data for the results table.

The search results table view’s delegate.
This object is responsible for, amongst other things, responding to the user’s selection of an item in the results table.

The search display controller’s delegate.
The delegate conforms to the UISearchDisplayDelegate protocol. It is notified of events such as when the search starts or ends, and when the search interface is displayed or hidden. As a convenience, it may also be told about changes to the search string or search scope, so that the results table view can be reloaded.

The search bar’s delegate.
This object is responsible for responding to changes in the search criteria.

Typically, the original view controller is used as the source object for the search results data source and delegate. You do not need to manually link up the data source and delegate with the view controller. As you insert the search bar into the view of Recipe Book View Controller, the appropriate connections to the search display controller are automatically configured. You can press the “control” key and click on the “Search Display Controller” to reveal the connections.

Search Display Controller Connections

Search Display Controller Connections

Both table views (i.e. the table view in Recipe Book View Controller and the search result table view) shares the same view controller to handle data population. If you refer to the code, these are the two methods being invoked when displaying table data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
   
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}

This explains why the search results show a full list of recipes regardless of your search term.

Implementing Search Filter

Obviously, to make the search works, there are a couple of things we have to implement/change:

  1. Implement methods to filter the recipe names and return the correct search results
  2. Change the data source methods to differentiate the table views. If the tableView being passed is the table view of Recipe Book View Controller, we show all recipes. On the other hand, if it’s a search result table view, only the search results are displayed.

First, we’ll show you how to implement the filter. Here we have an array to store all recipes. We create another array to store the search results. Let’s name it as “searchResults”.

1
2
3
4
@implementation RecipeBookViewController {
    NSArray *recipes;
    NSArray *searchResults;
}

Next, add a new method to handle the search filtering. Filtering is one of the common tasks in iOS app. The straightforward way to filter the list of recipes is to loop through all the names and filter the result with the if-statement. There is nothing wrong with such implementation. But iOS SDK offers a better way known as Predicate to handle search queries. By using NSPredicate (which is an object representation of a predicate), you write less code. With just two lines of code, it searches through all recipes and returns the matched results.

1
2
3
4
5
6
7
8
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate
                                    predicateWithFormat:@"SELF contains[cd] %@",
                                    searchText];
   
    searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}

Basically, a predicate is an expression that returns a Boolean value (true or false). You specify the search criteria in the format of NSPredicate and use it to filter data in the array. NSArray provides filteredArrayUsingPredicate: method which returns a new array containing objects that match the specified predicate. The SELF keyword in the predicate “SELF contains[cd] %@” refers to the objects being evaluated (i.e. recipes). The operator “[cd]” means the comparison is case- and diacritic-insensitive.

If you want to learn more about Predicate, check out Apple’s official documentation or the tutorial written by Peter Friese.

Implementing Search Display Controller Delegate

Now we’ve created a method to handle the data filtering. But when should it be called? Apparently the filterContentForSearchText: method is invoked when user keys in the search term. The UISearchDisplayController class comes with a shouldReloadTableForSearchString: method which is automatically called every time the search string changes. So add the following method in the RecipeBookViewController.m:

1
2
3
4
5
6
7
8
9
10
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
   
    return YES;
}

Display Search Results in searchResultsTableView

As explained earlier, we have to change the data source methods as to differentiate the table views (i.e. the table view in Recipe Book View Controller and the search result table view). It’s pretty easy to differentiate the table view. We simply compare the tableView object against the “searchResultsTableView” of the “searchDisplayController”. If the comparison is positive, we display the search results instead of all recipes. Here are the changes of the two methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];

    } else {
        return [recipes count];
       
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
   
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    }
   
    return cell;
}

Test the App Again

Once you complete the above changes, test your app again. Now the search bar should work properly!

Search Bar Complete

Handling Row Selection in Search Results

Despite the search works, it doesn’t respond to your row selection. We want to make it work like the recipe table view. When user taps on any of the search results, it’ll transit to the detail view displaying the name of selected recipe.

Earlier, we use Segue to link up the recipe table cell and detail view. (If you forgot how it was done, revisit the Segue tutorial to see how it works.)

Obviously, we have to create another Segue in Storyboard to define the transition between the search result and detail view. The problem is we can’t do that. The search result table view is a private variable of search display controller. It’s impossible to handle the row selection of the search results using Storyboard.

The search display table view, however, lets you interact with the user’s selection of the results table by using a delegate. When the user selects a row, the didSelectRowAtIndexPath: method will be called. Therefore, what we have to do is to implement the method:

1
2
3
4
5
6
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        [self performSegueWithIdentifier: @"showRecipeDetail" sender: self];        
    }
}

We simply invoke the performSegueWithIdentifier: method to manually trigger the “showRecipeDetail” segue. Before proceeding, try to run the app again. When you select any of the search results, the app shows the detail view with a recipe name. But the name is not always correct.

Referring to the prepareForSegue: method, we use the “indexPathForSelectedRow” method to retrieve the indexPath of the selected row. As mentioned earlier, the search results are displayed in a separate table view. But in our original prepareForSegue: method, we always retrieve the selected row from the table view of Recipe Book View Controller. That’s why we got the wrong recipe name in detail view. To make the selection of search results properly, we have to tweak the prepareForSegue: method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        RecipeDetailViewController *destViewController = segue.destinationViewController;
       
        NSIndexPath *indexPath = nil;

        if ([self.searchDisplayController isActive]) {
            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
            destViewController.recipeName = [searchResults objectAtIndex:indexPath.row];
           
        } else {
            indexPath = [self.tableView indexPathForSelectedRow];
            destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
        }
    }
   
}

We first determine if the user is using search. When searching, we retrieve the indexPath from searchResultsTableView, which is the table view for search results. Otherwise, we just get the indexPath from the table view of Recipe Book View Controller.

That’s it. Run the app again and the search selection should work as expected.

Search Results Selected

Tell Us What You Think

Hope you find this tutorial useful. If you like the tutorial and have any ideas about future tutorial, leave us comment and tell us what you think. We need your support to keep publishing free tutorials :-)

You May Like These:

  • http://www.facebook.com/profile.php?id=100001766866995 Keane Kwa

    Thanks, great tutorial.

  • Nazmul

    Great tutorial. I shall be grateful if you could make one tutorial for how to consume web service. Thanks!

    • http://www.simonblog.com Simon Ng

      Thanks for your suggestion. I’ll put it in my to-do list. :-)

    • http://www.simonblog.com Simon Ng

      Thanks for your suggestion. I’ll put it in my to-do list. :-)

      • Anonymous

        Could you make a tutorial where you can search the valueForKey:@”info” (for example) of every cell in your table view… In other words, can you make it so you can search a cell’s array instead of its title? Thanks.

  • Jake

    great tutorial this was really helpful

  • halunke

    Great tutorial as always! I would like to see something about further DetailView customizations (like images, lists, geo-location, weather or so) all in relation to what list-item you selected.
    Or something about CoreData :)

  • Fredrik

    Really good tutorial! Thanks!

  • Bubumuk

    Great tutorial. Thanks!

    I’d like to see something about CoreData and WebServices too like @7116a3171a2725aed8c83acd95a411cb:disqus and @fd7aca0e82906fbbf517913ee5a91232:disqus said.

    • http://www.simonblog.com Simon Ng

      Thanks for the suggestions. I’ll definitely cover both topics in the advanced tutorials.

    • http://www.simonblog.com Simon Ng

      Thanks for the suggestions. I’ll definitely cover both topics in the advanced tutorials.

  • Divz

    Great tutorial.This was really helpful.Thanks..

  • Bubumuk

    Hey, what do you think about a tutorial about pagination of the tableView?
    Thanks.

  • James

    Excellent tutorial. I got a challenge for you. Instead of displaying the name in the detail view display a description and image. So like an image of egg benedict and a description of it;)

    • http://www.simonblog.com Simon Ng

      Later I’ll definitely cover this part. But it shouldn’t be difficult to implement. I suggest to try it out yourself. In the detail view, add an image view and a label for the description. Then declare two instance variables in the detail view controller and link the variables with the UI elements. You can then pass the description and image to the detail view via segue. That’s very similar to the things we’ve done before.

      • James

        Thanks for the reply I will give it a shot:)

      • nancy

        please i wan a your urgent help:
        i wana add search bar that applied for all the application for example if i divide the recipe into two menu such as chicken and desserts how do i execute the search through these two table views….
        in other words how to determine the scope of my search bar…
        thank you sooo much in advance..

  • dar

    Awsome man. Been doing all your tutorials, never done xCode before. Really clear and helpfull.

  • Pingback: 第十三部分:在表视图中添加搜索栏 Search Bar (2) | EntLib.net 技术分享平台

  • Sharaf

    gr8 and very simple … i don’t have to be super in coding .. just follow the instructions and at the end everything will be working like charm ;) .. one small issue, it’s if you may specify where to copy and paste the code as .h .m and the name it will be easier for the rest … my self it worked out with me 100% .. Thank you so much

  • Mike

    I cant get it to work, can someone send me the finished code?

    • http://twitter.com/RodrRojas Rodrigo Rojas

      x2

  • Nel Martins

    Great tutorial. I have a question about the Accessory when a search is performed. Is there a way to set the Accessory to Disclosure Indicator to have the search list and non-search list appear identical?

  • Todd

    Like Mike below, I can’t get this to work either; entering text in the search bar does not display search results (the entire list remains in the view). I am on Xcode 4.5, and my guess is that 4.5 does not wire up the search widget automatically, at least not the same way. When I look at the connections on RecipeBookViewController, I don’t see all the same connections as shown in your screenshot (see my screenshot below).

    • Todd

      ah ha! My mistake — I used the ‘Search Bar’ component, instead of the ‘Search Bar and Search Display’ component. Now with the correct controller in place, search works perfectly.

      • http://www.simonblog.com Simon Ng

        Cool! Glad to hear the problem got solved.

  • http://twitter.com/shlns Shalin Shah

    How can I make a search bar in a listView instead of a tableView?

  • napolux

    Is there a way to get from the search tableview the original indexPath of the cell in the “parent” tableview?

  • Diogo

    I just didn’t understand why you create that method with the scope parameter if you are not using.

  • http://twitter.com/ash777ashot ASH

    how to work with NSMutableArray? (that contains title and text for detailView – both are nsstring…)
    how to make it filter titles?!!

  • Guest

    I got a problem… after entering the word in search bar nothing changes….

  • http://twitter.com/ash777ashot ASH

    I got a problem… after entering the word in search bar nothing changes. what to do?

  • Arseniy

    it just works ;) thank you!

  • http://twitter.com/jaytrixz Jay Santos

    Great tutorial as always! Can you also have the recipe tweaked to be grouped as food kinds sections i.e. high calorie, low calorie, etc. and have the table display it with the header named as the sections. It’ll make this tutorial super complete.

  • Appsicode

    When adding the Predicate. Im getting and error “use of undeclared identifier ‘filtercontentForSearchText” can someone help with with this please.

  • Me Gusta

    Thanks for the tutorial – from an iOS newbie

  • Malkit Singh

    thanks for useful tut….

  • tiendh

    It’s great

  • http://binceipt.com/ Mark Thien

    Hi Samuel, would you mind to provide us a download link for this project please? I got everything working except that when return from Detail View by tapping of upper left corner button, it goes back to the same Detail View screen then I have to tab again on the button to go back to the table view screen.

  • Pingback: Searchbar not returning search results (NSpredicate)

  • Pingback: Searchbar not returning search results (NSpredicate)

  • http://www.facebook.com/mozeryansky Michael Ozeryansky

    Thank you!

  • Basil Bourque

    Great tutorial. But it seems to have left out one step. The method:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    …needs to be updated. Rather than a single line of code:
    return [recipes count];
    …it needs an IF() statement to test if we are in Search mode. If searching, return count of “searchResults” rather than count of “recipes”.

    Complete method…

    - (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section
    {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [searchResults count];
    } else {
    return [recipes count];
    }
    }

  • Alan

    Excellent tutorials, more please!!!

  • http://twitter.com/fishfisher Erik Fisher

    First of all; your tutorials are absolutely amazing! I discovered this site a couple of days ago and I’ve been sitting with it ever since!

    A quick question popped up during this one. At the prepare ForSegue I am able to pass the title to the DetailView, but I am struggling to pass along the image I also have in the DetailView.

    I was able to do it by changing the image names to be exactly the same as the recipeNames. That way I could use [UIImage imageNamed:[searchResults objectAtIndex:indexPath.row]];
    But that doesn’t seem like a very good way of doing it..

    Can you show me some coding magic on this topic?

    Thanks again!

  • http://twitter.com/fishfisher Erik Fisher

    First of all; your tutorials are absolutely amazing! I discovered this site a couple of days ago and I’ve been sitting with it ever since!

    A quick question popped up during this one. At the prepare ForSegue I am able to pass the title to the DetailView, but I am struggling to pass along the image I also have in the DetailView.

    I was able to do it by changing the image names to be exactly the same as the recipeNames. That way I could use [UIImage imageNamed:[searchResults objectAtIndex:indexPath.row]];
    But that doesn’t seem like a very good way of doing it..

    Can you show me some coding magic on this topic?

    Thanks again!

  • rohan

    Hey, great tutorial, but I get a SIGABRT error when I click on the tab I put the search bar in.

  • javifernandezr

    Very Useful

  • mevdev

    Great tutorial. Thanks!

  • http://www.facebook.com/profile.php?id=100000099922270 Lafayette Kirsi Noel

    Good Day Simon! I got stuck up in Displaying search results in searchResultsTableView. When I tried running it and search something, the app terminates and a SIGABRT will occur under main in ” return UIApplicationMain(argc, argv, nil, NSStringFromClass (RecipeBookAppDelegate class])); “.
    Im using this syntax of RMD from the previous tutorial’s comments

    Recipe *thisRecipe=[recipes objectAtIndex:indexPath.row];cell.textLabel.text=thisRecipe.name;

    in order to display the recipe names on tableview.. Im not quite sure if it’s connected to the problem in searching and displaying.

  • Giancarlo Leonio

    Awesome tutorial Simon! Just was I needed. I made a list of resources on this topic of implementing a Search Bar in TableView. Other may find useful: http://www.verious.com/board/Giancarlo-Leonio/implementing-an-ios-search-bar-in-table-view

  • Khalid Mehmood Awan

    things are getting a little difficult now :D ….

    anyways, excellent work…

  • http://www.facebook.com/paullauyc Paul Lau

    Great tutorial !! ^_^

    Do you have any idea to customize the TableCell for UISearchDisplayController ? Like your Tutorial #4 – Customize Table View Cells for UITableView.

    Many Thanks…

  • Felix

    Hey,
    I have some problems, it throws an error “can’t use in/contains operator with collection” when I try to write something into the searchbar.

    Here’s my code:

    //
    // RecipeViewController.m
    // CustomTableView
    //
    // Created by Simon on 1/1/13.
    // Copyright (c) 2013 Appcoda. All rights reserved.
    //

    #import “RecipeViewController.h”
    #import “Recipe.h”

    @interface RecipeViewController ()

    @end

    @implementation RecipeViewController {
    NSArray *recipes;
    NSArray *searchResults;
    }

    - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
    {
    NSPredicate *resultPredicate = [NSPredicate
    predicateWithFormat:@"SELF contains[cd] %@”,
    searchText];

    searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
    }

    -(BOOL)searchDisplayController:(UISearchDisplayController *)controller
    shouldReloadTableForSearchString:(NSString *)searchString
    {
    [self filterContentForSearchText:searchString
    scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
    objectAtIndex:[self.searchDisplayController.searchBar
    selectedScopeButtonIndex]]];

    return YES;
    }

    - (id)initWithStyle:(UITableViewStyle)style
    {
    self = [super initWithStyle:style];
    if (self) {
    // Custom initialization
    }
    return self;
    }

    - (void)viewDidLoad
    {
    [super viewDidLoad];

    self.navigationItem.title = @”Minecraft IDs”;
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@”Back” style:UIBarButtonItemStyleBordered target:nil action:nil];
    [[self navigationItem] setBackBarButtonItem:backButton];

    // Create recipe array
    Recipe *recipe1 = [Recipe new];
    recipe1.name = @”Mushroom Risotto”;
    recipe1.detail = @”Delicious mushroom risotto made with vegetable broth, cream, and a variety of fresh vegetables. Serve as a side dish or filling main course.”;
    recipe1.imageFile = @”mushroom_risotto.jpg”;

    Recipe *recipe2 = [Recipe new];
    recipe2.name = @”Egg Benedict”;
    recipe2.detail = @”30 min”;
    recipe2.imageFile = @”egg_benedict.jpg”;

    Recipe *recipe3 = [Recipe new];
    recipe3.name = @”Full Breakfast”;
    recipe3.detail = @”20 min”;
    recipe3.imageFile = @”full_breakfast.jpg”;

    Recipe *recipe4 = [Recipe new];
    recipe4.name = @”Hamburger”;
    recipe4.detail = @”30 min”;
    recipe4.imageFile = @”hamburger.jpg”;

    Recipe *recipe5 = [Recipe new];
    recipe5.name = @”Ham and Egg Sandwich”;
    recipe5.detail = @”10 min”;
    recipe5.imageFile = @”ham_and_egg_sandwich.jpg”;

    recipes = [NSArray arrayWithObjects:recipe1, recipe2, recipe3, recipe4, recipe5, nil];
    }

    - (void)didReceiveMemoryWarning
    {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

    #pragma mark – Table view data source

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
    // Return the number of sections.
    return 1;
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [searchResults count];

    } else {
    return [recipes count];

    }
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *CellIdentifier = @”Cell”;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell…
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if (tableView ==self.searchDisplayController.searchResultsTableView) {
    Recipe *recipe = [searchResults objectAtIndex:indexPath.row];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:recipe.imageFile];

    UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
    recipeNameLabel.text = recipe.name;

    UILabel *recipeDetailLabel = (UILabel *)[cell viewWithTag:102];
    recipeDetailLabel.text = recipe.detail;
    }

    // Display recipe in the table cell
    Recipe *recipe = [recipes objectAtIndex:indexPath.row];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:recipe.imageFile];

    UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
    recipeNameLabel.text = recipe.name;

    UILabel *recipeDetailLabel = (UILabel *)[cell viewWithTag:102];
    recipeDetailLabel.text = recipe.detail;

    return cell;
    }

    /*
    // Override to support conditional editing of the table view.
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
    // Return NO if you do not want the specified item to be editable.
    return YES;
    }
    */

    /*
    // Override to support editing the table view.
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

    /*
    // Override to support rearranging the table view.
    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
    {
    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
    {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
    }
    */

    #pragma mark – Table view delegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    // Navigation logic may go here. Create and push another view controller.
    /*
    *detailViewController = [[ alloc] initWithNibName:@”" bundle:nil];
    // …
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    */
    }

    @end

    • Yanet

      You have to put this in the search query (specify the attribute to search, ‘name’) :
      SELF.name contains[cd] %@

      Alsoto visualize the result have to put this (look the self before tableView):
      UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  • rajohns

    just in case anyone made the same mistake I did and clicking a search result always shows the same recipe detail:

    i had already implemented the didSelectRowAtIndexPath method to deselect the option. If you did this, make sure you put the “[tableView deselectRowAtIndexPath:indexPath animated:YES];” line AFTER the performSegueWithIdentifier line. Otherwise the row will be deselected, and the indexPath will not evaluate to anything in the prepareForSegue function when the search display is active.

  • Yanet

    Issue:

    I’m working with a Customized Cell and the searchTableView is not picking those cells. What I mean is that I’m trying to change the background and size of the cells for the searchTableView so it looks more like my tableView before the search. However is not working. Any idea?

  • Htun Lin Aung

    i have a search bar with two scope bar buttons. if i click the search button, i need to check which scope bar button was clicked.
    How to check which button i clicked?