In this recipe we will learn how to search through our Table View to filter list items.
Following on from our previous recipe, we will learn how to use the UISearchBar
control to allow us to filter and narrow down the results of our book details.
To begin, follow these simple steps as outlined in the following order:
MainStoryboard.storyboard
file from the Project Navigator window.UISearchBar
) Search Bar and Search Display Controller control to the top of the navigation bar of our (UITableViewController
) control that we added in previous steps.outlet
method for the search bar and name it filteredResults
. BooksViewController.h
interface file from the Project Navigator window.// BooksViewController.h // BooksLibrary // Created by Steven F Daniel on 03/12/12. // Copyright (c) 2012 GenieSoft Studios. All rights reserved. #import <UIKit/UIKit.h> #import "Books.h" @interface BooksViewController : UITableViewController <UISearchBarDelegate>{ ... ... IBOutlet UISearchBar *filteredResults; } ... ... // Property getters and setters for our UI @property (strong, nonatomic) IBOutlet UISearchBar *filteredResults;
UISearchBarDelegate
object so that we can access the properties and methods. Our next step is to, start adding the additional content to our BooksViewController
class that will provide us with the ability to filter the results of our list.BooksViewController.m
implementation file from the Project Navigator window and create the following code sections, as specified in the code snippet.//
// BooksViewController.m
// BooksLibrary
//
// Created by Steven F Daniel on 03/12/12.
// Copyright (c) 2012 GenieSoft Studios. All rights reserved.
//
#import "BooksViewController.h"
@implementation BooksViewController
@synthesize fetchedResultsController;
@synthesize managedObjectContext;
@synthesize btnAdd;
@synthesize btnSortOrder;
@synthesize btnConnect;
@synthesize btnTransfer;
@synthesize filteredResults;
#pragma mark method called by the UISearchBar Delegates
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
// Only show the Search Bar's cancel button while in edit mode
filteredResults.showsCancelButton= YES;
filteredResults.autocorrectionType =
UITextAutocorrectionTypeNo;
}
#pragma mark Hides our Search Bar's cancel button when not in edit mode
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
filteredResults.showsCancelButton = NO;
}
#pragma mark reload our contact details
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[self populateBookDetails];
}
#pragma mark use an NSPredicate combined with the fetchedResultsController to perform the search
-(void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
if (![destinationSearchBar.text isEqualToString:@""]) {
NSPredicate *predicate =[NSPredicate
predicateWithFormat:@"publisher contains[cd] %@",
self.filteredResults.text];
[fetchedResultsController.fetchRequest
setPredicate:predicate];
}
else {
// We have hit the cancel button, reload our TableView
[filteredResults resignFirstResponder];
[self.tableView reloadData];
return;
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
// Handle the error that was caught by the exception
NSLog(@"Unresolved error %@, %@", error, [error
userInfo]);
exit(-1);
}
// Return the number of rows to populate our Table View
// controller with.
fetchedObjects = fetchedResultsController.fetchedObjects;
// reload the TableView Controller and hide the keyboard.
[filteredResults resignFirstResponder];
[self.tableView reloadData];
// Display the total number of matching records found.
NSString *searchResults = [[NSString alloc]
initWithFormat:@"%d matching record(s)
found.",[fetchedObjects count]];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Search Results"
message:searchResults
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
In this recipe, we start by extending our
BooksViewController
class to use the UISearchBarDelegate
class protocols so that we have access to its properties and methods and then change the appearance of the Search bar when a user taps in it. Next, we specify to show the Cancel button when the user is in Edit mode, and then
turn off the Auto Correction feature and then proceed to hide the Cancel button of the Search bar when the user has finished with editing. In our next step, we call our
populateBookDetails
method to get the updated records from the database, and populate this to our Table View control before proceeding to cycle through our data source and select those objects that have the occurrence of the search string.
Finally, we proceed to reload our Table View with the search data that was returned to be matching, and then display the total number of records that match our search string within a UIAlertView
dialog box. If the Search criterion is empty, we perform a comparison using the isEqualToString
method and check to see if the string is empty. We then resign the keyboard and reload all book details from our data model.