Go Back   MacRumors Forums > Apple Systems and Services > Programming > iPhone/iPad Programming

Reply
 
Thread Tools Search this Thread Display Modes
Old Jan 21, 2010, 08:43 PM   #1
tommyh1122
macrumors newbie
 
Join Date: May 2008
UISearchBar

Hello,

I am new to programming and trying to get a SearchBar to work correctly and hoping someone can show me what I am doing wrong. I have the SearchBar created and when the "search" button is clicked the SearchBar is created along with the segment controls. When you click in the Search the keyboard comes up but when you type it does not search the data. I am not sure what I am doing wrong!!!! I am attaching the ViewController that has the code so that hopefully someone can show me what I am doing wrong.

Code:
- (void)viewDidLoad {
    // Configure the navigation bar
    self.title = @"United States";

	UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
																					target:self
																					action:@selector(searchBar:)];
	self.navigationItem.rightBarButtonItem = rightBarButton;

	
	UISearchBar *mySearchBar = [[UISearchBar alloc] init];
	mySearchBar.tintColor = [UIColor redColor];
	[mySearchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"All",@"Name",@"State",nil]];
	mySearchBar.delegate = self;
	[mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
	[mySearchBar sizeToFit];
	self.tableView.tableHeaderView = mySearchBar;
	
	/*
	 set up the searchDisplayController programically
	 */
	searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
	[self setSearchDisplayController:searchDisplayController];
	[searchDisplayController setDelegate:self];
	[searchDisplayController setSearchResultsDataSource:self];
	
	// create a filtered list that will contain products for the search results table.
	self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];
	
	// restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm)
	{
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];
        
        self.savedSearchTerm = nil;
    }
	
	//[self.tableView reloadData];
	//self.tableView.scrollEnabled = YES;
	[mySearchBar release];
	
    
    // Set the table view's row height
    self.tableView.rowHeight = 54.0;
	
	NSError *error = nil;
	if (![[self fetchedResultsController] performFetch:&error]) {

		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
	}		
}

- (void)viewWillAppear:(BOOL)animated {
	/*
	 Hide the search bar
	 */
	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
	
	
	NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
	[self.tableView deselectRowAtIndexPath:tableSelection animated:NO];
}

- (void)viewDidUnload
{
	// Save the state of the search UI so that it can be restored if the view is re-created.
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
	
	self.filteredListContent = nil;
}

- (void)dealloc {
	[fetchedResultsController release];
	[managedObjectContext release];
	
	[listContent release];
	[filteredListContent release];
	
    [super dealloc];
}

#pragma mark -
#pragma mark Recipe support

- (void)showRecipe:(Recipe *)recipe animated:(BOOL)animated {
    // Create a detail view controller, set the recipe, then push it.
    RecipeDetailViewController *detailViewController = [[RecipeDetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
    detailViewController.recipe = recipe;
    
    [self.navigationController pushViewController:detailViewController animated:animated];
    [detailViewController release];
}


#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
 
	NSInteger count = [[fetchedResultsController sections] count];
    
	if (count == 0) {
		count = 1;
	}
    return count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSInteger numberOfRows = 0;
	
    if ([[fetchedResultsController sections] count] > 0) {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
        numberOfRows = [sectionInfo numberOfObjects];

    }
	
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
        return [self.filteredListContent count];
    }
	else
	{
         return numberOfRows;
	}
		
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Dequeue or if necessary create a RecipeTableViewCell, then set its recipe to the recipe for the current row.
    static NSString *RecipeCellIdentifier = @"RecipeCellIdentifier";
    
    RecipeTableViewCell *recipeCell = (RecipeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RecipeCellIdentifier];
    if (recipeCell == nil) 
	{
        recipeCell = [[[RecipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RecipeCellIdentifier] autorelease];
		recipeCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
	[self configureCell:recipeCell atIndexPath:indexPath];
    
	Recipe *recipe = nil;
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
        recipe = [self.filteredListContent objectAtIndex:indexPath.row];
    }
	else
	{
        recipe = [self.listContent objectAtIndex:indexPath.row];
    }
	
	recipeCell.textLabel.text = recipe.name;

	return recipeCell;
}

- (void)configureCell:(RecipeTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // Configure the cell
	Recipe *recipe = (Recipe *)[fetchedResultsController objectAtIndexPath:indexPath];
    cell.recipe = recipe;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Recipe *recipe = (Recipe *)[fetchedResultsController objectAtIndexPath:indexPath];
    
    [self showRecipe:recipe animated:YES];
	
	//Recipe *recipe = nil;
	
	UIViewController *detailsViewController = [[UIViewController alloc] init];
	
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
        recipe = [self.filteredListContent objectAtIndex:indexPath.row];
    }
	else
	{
        recipe = [self.listContent objectAtIndex:indexPath.row];
    }
	detailsViewController.title = recipe.name;
    
    [[self navigationController] pushViewController:detailsViewController animated:YES];
    [detailsViewController release];
	
}


#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
    // Set up the fetched results controller if needed.
    if (fetchedResultsController == nil) {
        // Create the fetch request for the entity.
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        // Edit the entity name as appropriate.
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];
        
        // Edit the sort key as appropriate.
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
        aFetchedResultsController.delegate = self;
        self.fetchedResultsController = aFetchedResultsController;
        
        [aFetchedResultsController release];
        [fetchRequest release];
        [sortDescriptor release];
        [sortDescriptors release];
    }
	
	return fetchedResultsController;
}    

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
	// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
	[self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
	UITableView *tableView = self.tableView;
	
	switch(type) {
		case NSFetchedResultsChangeInsert:
			[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
			break;
			
		case NSFetchedResultsChangeDelete:
			[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
			break;
			
		case NSFetchedResultsChangeUpdate:
			[self configureCell:(RecipeTableViewCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
			break;
			
		case NSFetchedResultsChangeMove:
			[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
			// Reloading the section inserts a new row and ensures that titles are updated appropriately.
			[tableView reloadSections:[NSIndexSet indexSetWithIndex:newIndexPath.section] withRowAnimation:UITableViewRowAnimationFade];
			break;
	}
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
	switch(type) {
		case NSFetchedResultsChangeInsert:
			[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
			break;
			
		case NSFetchedResultsChangeDelete:
			[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
			break;
	}
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
	[self.tableView endUpdates];
}


#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	
	 //Update the filtered array based on the search text and scope.
	[self.filteredListContent removeAllObjects]; // First clear the filtered array.
	
	
	for (Recipe *recipe in listContent)
	{
		if ([scope isEqualToString:@"All"] || [recipe.name isEqualToString:scope])
		{
			NSComparisonResult result = [recipe.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
			if (result == NSOrderedSame)
			{
				[self.filteredListContent addObject:recipe];
			}
		}
	}
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:
	 [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
	 [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}
	
#pragma mark -
#pragma mark Memory management

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
	/*
	 Hide the search bar
	 */
	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
}

#pragma mark -

-(void)searchBar:(id)sender{
	[searchDisplayController setActive:YES animated:YES];
}

@end
Thanks
Mike
tommyh1122 is offline   0 Reply With Quote
Old Jan 22, 2010, 12:34 AM   #2
dejo
Moderator
 
dejo's Avatar
 
Join Date: Sep 2004
Location: The Centennial State
Did you implement the searchBar:textDidChange: UISearchBarDelegate method?
__________________
dejo is offline   0 Reply With Quote
Old Jan 22, 2010, 07:05 AM   #3
tommyh1122
Thread Starter
macrumors newbie
 
Join Date: May 2008
I did not have a searchBar:textDidChange method. I added this code but my table is now cleared out????

Code:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	[self.tableView removeAllObjects];
	if([searchText isEqualToString:@""]||searchText==nil){
		[self.tableView reloadData];
		return;
	}
	NSInteger counter = 0;
	for(NSString *name in filteredListContent)
	{
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
		NSRange r = [name rangeOfString:searchText];
		if(r.location != NSNotFound)
		{
			if(r.location==0)
			{
				[self.filteredListContent addObject:name];
			}
		}
		counter++;
		[pool release];
	}
	[self.tableView reloadData];
}
tommyh1122 is offline   0 Reply With Quote
Old Jan 22, 2010, 10:36 AM   #4
dejo
Moderator
 
dejo's Avatar
 
Join Date: Sep 2004
Location: The Centennial State
Looks like you are looping through filteredListContent and then adding objects to filteredListContent. That seems wrong.
__________________
dejo is offline   0 Reply With Quote
Old Jan 23, 2010, 09:46 AM   #5
tommyh1122
Thread Starter
macrumors newbie
 
Join Date: May 2008
I updated the searchBar:textDidChange method and I no longer receive any warnings but when I run the application my table is no longer populated.

Code:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	[self.filteredListContent removeAllObjects];
	if([searchText isEqualToString:@""]||searchText==nil){
		[self.tableView reloadData];
		return;
	}
	NSInteger counter = 0;
	for (Recipe *recipe in listContent)
	{
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
		NSRange r = [recipe.name rangeOfString:searchText];
		if(r.location != NSNotFound)
		{
			if(r.location==0)
			{
				[self.filteredListContent addObject:recipe];
			}
		}
		counter++;
		[pool release];
	}
	[self.tableView reloadData];
}
tommyh1122 is offline   0 Reply With Quote
Old Jan 23, 2010, 05:21 PM   #6
dejo
Moderator
 
dejo's Avatar
 
Join Date: Sep 2004
Location: The Centennial State
And you're sure that recipes are now being added to filteredListContent?
__________________
dejo is offline   0 Reply With Quote
Old Jan 23, 2010, 08:52 PM   #7
tommyh1122
Thread Starter
macrumors newbie
 
Join Date: May 2008
I have the table populated now it needed a Clean and Build. When I try the search it does not come back with results. Any other suggestions on how to get the search to work?

Thanks
tommyh1122 is offline   0 Reply With Quote
Old Jan 23, 2010, 09:26 PM   #8
dejo
Moderator
 
dejo's Avatar
 
Join Date: Sep 2004
Location: The Centennial State
Quote:
Originally Posted by tommyh1122 View Post
Any other suggestions on how to get the search to work?
Look into your rangeOfString usage and make sure you are getting matches where you expect them.
__________________
dejo is offline   0 Reply With Quote

Reply
MacRumors Forums > Apple Systems and Services > Programming > iPhone/iPad Programming

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Similar Threads
thread Thread Starter Forum Replies Last Post
resize UISearchBar kikko088 iPhone/iPad Programming 3 Dec 14, 2012 09:40 AM

Forum Jump

All times are GMT -5. The time now is 06:23 AM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC