Search code examples
objective-carraysnsarraysearchbarnsunknownkeyexception

NSUnknownKeyException while using SearchBar. this class is not key value coding-compliant for the key name


I've had a look through posts that other people have posted with this sort of error, but non in a UISearchBar, and none that I can relate my issue to:

In short, I'm playing with searchBars and trying to build the basics.

I have 2 arrays

@interface ViewController ()
{
    NSMutableArray *dataList;
    NSArray *searchResults;
}

I've populated my dataList array using the following:

dataList = [[NSMutableArray alloc] init];

[dataList addObject:@"This is row 1"];
[dataList addObject:@"That is row 2"];
....
[dataList addObject:@"More data in 20"];

I set up my searchDisplayController:

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString*) searchString
{
    [self filterContentForSearchText:searchString
                           scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                  objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    return YES;
}

and I have a filter function:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {    
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

    searchResults = [dataList filteredArrayUsingPredicate:resultPredicate];
}

It's in the last filter function that I get an error on the last line beginning searchResults =

2014-07-29 17:47:16.056 TestSearch[44628:60b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFConstantString 0x1000069c8> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'
*** First throw call stack:
...
...
...

Any ideas?

I have tried using an NSArray instead of NSMutableArray but I get the same error.

The tableView is filling up OK with the data, so no problem there.


Solution

  • name is not a property of an NSString object. use self for the predicate:

    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchText];