How to implement searching in UITableView

How to implement searching in UITableView

 

So, today we are going to see how to  implement Searching of data in UITableView.
Given below is the snapshot of what will our app look like.

iPhone Application Development

So lets get started :-


1.) Creating a new project

The first step is to create a new project. For this we need to :-

a.) launch Xcode.
b.) click on File -> New Project.
c.) select Application (under iOS).
d.) select View-Based Application project template.
e.) Under Product , choose iPad.
f.) click on choose.
g.) save the project and  name it “search”.

iPhone Application Development

This is how the list of files look like in Xcode.

iPhone Application Development

2.)Building the Interface


Go to “Resources” folder and click “searchViewController.xib” file. This will launch the “Interface Builder” which consists of few windows.

a.)Now we will go to the “Library window” and from there we will select the “Search Bar” and “Table View” drag it to the “View window”.
b.) We will make the interface as shown in the figure and name the objects according to it.

iPhone Application Development

3.)Writing Code

a.)So Code for “searchViewController.h” file


There would be a piece of code that Xcode has already written for you. Here’s what the whole code will look like.

#import <UIKit/UIKit.h>

@interface searchViewController : UIViewController
<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>{
	NSMutableArray *listOfItems;
	UITableView *tableView;
	IBOutlet UISearchBar *sBar;
	NSMutableArray *copyListOfItems;
	BOOL searching;

}
@property(nonatomic,retain)UITableView *tableView;
-(void) searchTableView;
- (void) doneSearching_Clicked:(id)sender;

@end

Here  we have  the delegates for the UUISearchBar, TableView and TableViewDataSource.

We  also declare a TableView object, a SearchBar object and few other objects which needs will be explained in the next step.

We declare two methods “searchTableView” and “doneSearching_Clicked” which will be called for searching and end searching respectively.

 

b.)Code for “searchViewController.m” file

 

In this part we synthesize the “tableView” object and in “viewDidLoad” method we allocate the objects to the “MutuableArray”.

We implement the methods “searchBarDidBeginEditing” and “doneSearching_Clicked”.

Here we allocate the number of sections and number of rows in the TableView.

In “searchTableView” object we implement the logic for search.

We define a temporary string that contains the string entered in the “SearchBar”.

Then  this  string is matched with the objects of the array in the “TableView” and the results are  stored in another array “copyListOfItems” and is displayed.

4.)Building the Connections

#import "searchViewController.h"

@implementation searchViewController
@synthesize tableView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Countries";
	listOfItems = [[NSMutableArray alloc] initWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway",@"Sri Lanka",@"China", @"New Zealand", @"Greece", @"Rome", @"Ireland",@"India", @"U.S.A", nil];

	//Initialize the copy array.
	copyListOfItems = [[NSMutableArray alloc] init];

	//Set the title
	self.navigationItem.title = @"Countries";
    searching = NO;
	sBar.autocorrectionType = UITextAutocorrectionTypeNo;
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {

	searching = YES;
	self.tableView.scrollEnabled = NO;

		}

- (void) doneSearching_Clicked:(id)sender {

	[sBar resignFirstResponder];

	self.navigationItem.rightBarButtonItem = nil;
	self.tableView.scrollEnabled = YES;

}

- (NSIndexPath *)tableView : (UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	return indexPath;

}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

	//Remove all objects first.
	[copyListOfItems removeAllObjects];

	if([searchText length] > 0) {

		[self searchTableView];

	}
	else{
		searching=NO;

	}
	[self.tableView reloadData];

}

- (void) searchTableView {

	searching = YES;
	NSString *searchText = sBar.text;
	NSMutableArray *searchArray = [[NSMutableArray alloc] init];

	[searchArray addObjectsFromArray:listOfItems];

	for (NSString *sTemp in searchArray)
	{
		NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

		if (titleResultsRange.length > 0)
			[copyListOfItems addObject:sTemp];
	}

	[searchArray release];
	searchArray = nil;
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

	return 1;

}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	if (searching)
		return [copyListOfItems count];
	else {
		return [listOfItems count];
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}

	// Set up the cell...

	if(searching)
		cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
		else {

			//First get the dictionary object

			cell.textLabel.text = [listOfItems objectAtIndex:indexPath.row];
		}

	return cell;
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
	[sBar release];
	[tableView release];
	[listOfItems release];
    [super dealloc];
}

@end

Our next step is to build the connections between the code we have written with our Interface elements.

a.)So we click on the “searchViewController.xib” in the “Resources” folder to launch “Interface Builder.

b.)There in the “Document window” we select “File’s Owner” and right click it.

c.)Now a window pops up which shows all the “Outlets and Actions” defined by us.

d.)Do the connections as shown below.

iPhone Application Development

5.)Build and Run

iPhone Application Development
Now finally we have to go to the Xcode and there at the top bar we see “Build and Run”. Just click it to run the application. Make sure we have saved our application before doing this.

So finally our app will look something like this:-

iPhone Application Development