I have a working Table view controller that populates based on xml files corresponding to the previous table view controller. Everything works just fine until I tried adding a UISearchDisplayController.
After going through some tutorials I tried implementing their code but my app keeps crashing with the below error:
** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x175949e0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.' **
Here are some relevant code snippets for my .m file:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.searchResults.count;
} else {
return _Refs.SubReference.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SubRefCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TableCell"forIndexPath:indexPath];
if (cell == nil) {
NSLog(@"Error with nil cell");
}
int row=[indexPath row];
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.subRefLabel.text = self.searchResults[row];
cell.subRefDescLabel.text = _Refs.SubRefDesc[row]; //fix later
} else {
//set all the cells with the Sub Reference names and their descriptions
cell.subRefLabel.text = _Refs.SubReference[row];
cell.subRefDescLabel.text = _Refs.SubRefDesc[row];
}
return cell;
}
#pragma Search Methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
//self.searchSubRef = _Refs.SubReference;
NSLog(@"Here is a list of refs %@",_Refs.SubReference);
//crashes right after this line
self.searchResults = [_Refs.SubReference filteredArrayUsingPredicate:resultPredicate];
NSLog(@"Test");
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
I do have custom cells and checked for '!' on all the outlets for both my tableview controller and my table view cell but they all seemed to be ok. I also tried to open the storyboard as source code and look for outlets called 'name' but no luck.
Any ideas what is going wrong and why the app crashes as soon as I try typing into the search bar?
I found the problem was with my NSPredicate.
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
It is trying to look for a reusable cell identifier called name
which I never declared. So a simple fix for this was to use SELF
instead.
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchText];