Return to Snippet

Revision: 26538
at April 30, 2010 08:57 by espinallab


Initial Code
//Add the search bar delegate to the header file
<UISearchBarDelegate>

        //Declare this in the header file.
	UISearchBar *searchBar;
	UISearchDisplayController *searchDC;




	// Create a search bar - you can add this in the viewDidLoad
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	self.searchBar.delegate = self;
	self.tableView.tableHeaderView = self.searchBar;
	
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;



//Then add this to your fetch or query method
#pragma mark -
#pragma mark Fetch Objects

- (void) fetchObjects
{
	// Create a basic fetch request
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	[fetchRequest setEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:MANAGED_OBJECT_CONTEXT]];
	
	// Add a sort descriptor
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:nil];
	NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
	[fetchRequest setSortDescriptors:descriptors];
	[sortDescriptor release];
	
	// Recover query
	NSString *query = self.searchBar.text;
	if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];
	
	// Init the fetched results controller
	NSError *error;
	self.results = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:MANAGED_OBJECT_CONTEXT sectionNameKeyPath:@"section" cacheName:@"Root"];
	self.results.delegate = self;
	if (![[self results] performFetch:&error])	NSLog(@"Error: %@", [error localizedDescription]);
	
	[self.results release];
	[fetchRequest release];
	
	//[self.tableView reloadData];
}

Initial URL
http://www.espinallab.com

Initial Description
This might look complicated but actually it was easy than what I though to integrate.  I'm using it with Core Data, but I'm sure you can use it with any data type.

Initial Title
Adding a Search Bar to a UITableView

Initial Tags

                                

Initial Language
Objective C