Reputation: 251
I'm developing an app in Xcode in Objective-C. The app has a TableView with restaurants. My problem is that when I use the SearchBar the filter is case sensitive and I want to get a case insensitive search.
I know I have to change my searchBar textDidChange
method, and I looking for help but I don't know how to change it in my case. Can someone help me? Thank you very much.
This is my searchBar textDidChange
method:
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
filteredRest = [[NSMutableArray alloc] init];
for (Restaurant *item in originData) {
if ([item.title containsString:searchText]) {
[filteredRest addObject:item];
}
}
//Reload our table view
[self.tableView reloadData];
}
Thank you.
Upvotes: 1
Views: 934
Reputation: 79
One more best solution.
if (!([item.title rangeOfString:searchText options:NSCaseInsensitiveSearch].location == NSNotFound))
{
[filteredRest addObject:item];
}
Upvotes: 0
Reputation: 3501
This is how you should update the code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title CONTAINS[cd] %@", searchText];
filteredRest = [originData filteredArrayUsingPredicate:predicate]
//Reload our table view
[self.tableView reloadData];
}
Upvotes: 1
Reputation: 11127
Change this line
if ([item.title containsString:searchText]) {
[filteredRest addObject:item];
}
With this
if ([[item.title lowercaseString]containsString:[searchText lowercaseString]]) {
[filteredRest addObject:item];
}
Upvotes: 4