I want to be able to add a Search feature to my table view. The table lists various store locations. I want the user to be able to filter by city. I have been thinking of adding a dropdown list somehow, perhaps in a tableviewcell to create the filter. Has anyone done this who could help me out?
I already have a search bar control in the table view but it only searches by one field of the records. How do I decide or select which field the search bar actually looks for in my data? This is my code:
#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.filteredResultsArray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
[self.filteredResultsArray = [NSMutableArray arrayWithArray:[self.dates filteredArrayUsingPredicate:predicate]] retain];
}
#pragma mark - UISearchDisplayController Delegate Methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// Tells the table data source to reload when text changes
[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 {
// Tells the table data source to reload when scope bar selection changes
[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;
}
my self.dates array is populated like so:
- (void)loadRecordsFromCoreData {
[self.managedObjectContext performBlockAndWait:^{
[self.managedObjectContext reset];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:self.entityName];
[request setSortDescriptors:[NSArray arrayWithObject:
[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]]];
self.dates = [self.managedObjectContext executeFetchRequest:request error:&error];
}];
}
Does it have to do with the initWithEntityName…
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];That predicate determines which field is being searched in your data – the name field in this case. If you want to search on a different field just change the SELF.name to SELF.city or whatever the other field is. If you want to search on multiple fields or use additional logic in the filter, check out Apple’s NSPredicate Programming Guide.