I am trying to add a searchBarController into my tableView. I am not getting any errors when I build the app, but when I start typing into the searchBar, the app throws an exception and crashes.
The line that causes the crash is commented below in the very last block of code. Does anyone know what might be going wrong here? Thanks much!
Relevant Parts of my .h file:
@interface BusinessesViewController : UITableViewController<CLLocationManagerDelegate,
UISearchDisplayDelegate> {
IBOutlet UITableView *mainTableView;
NSArray *businesses;
NSMutableData *data;
NSArray *filteredBusinesses;
}
Relevant Parts of my viewDidLoad Method:
- (void)viewDidLoad {
filteredBusinesses = [[NSArray alloc]init];
}
NumberOfRowsInSection Method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredBusinesses count];
}
else {
return [businesses count];
}
}
CellForRowAtIndexPath Method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
BusinessesTableViewCell *cell = (BusinessesTableViewCell *)[tableView
dequeueReusableCellWithIdentifier:@"MainCell"];
if (tableView == self.searchDisplayController.searchResultsTableView) {
[cell.businessMainLabel setText:[[filteredBusinesses
objectAtIndex:indexPath.row]objectForKey:@"name"]];
}
else {
[cell.businessMainLabel setText:[[businesses
objectAtIndex:indexPath.row]objectForKey:@"name"]];
}
return cell;
}
Predicate and SearchDisplayController Methods:
- (void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"beginswith[cd] %@",
searchText];
//THIS LINE OF CODE CAUSES THE CRASH
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:
[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
Your predicate is wrong, the key is missing. From the other code it looks as if
the objects in businesses
have a "name" property, so the predicate should be
[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText]
^key ^operator ^value