在 UITableView 问题中搜索字典值和键并显示

Searching Dictionary Values & Keys & Displaying in UITableView issues

我正在尝试更新我的搜索显示控制器,但现在,我是这样设置的:

 NSString *path = [[NSBundle mainBundle] pathForResource:@"Documents"
                                                 ofType:@"plist"];

searchDict = [NSDictionary dictionaryWithContentsOfFile:path];
allsearchDictKeys = [searchDict allKeys];

我用 NSPredicate 搜索它

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    searchResults = [[NSMutableArray alloc] init];
    [searchDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
    if ([key isEqualToString:searchText] || [obj isEqualToString:searchText] ) {
        [searchResults addObject:key];
        NSLog(@"search is %@", searchResults);
    }}];
}

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

并在 table 视图中显示结果,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *defaultIdentifier = @"Cell";
 UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:defaultIdentifier];
 if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:defaultIdentifier];
}

cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [searchDict valueForKey:cell.textLabel.text];

return cell;
}

我希望能够搜索值 键,所以我实现了这个:

allsearchDictValues = [searchDict allValues];

//Trying to search complete plist where searchArray is NSMutableArray
searchArray = [[NSMutableArray alloc] init];
[searchArray addObjectsFromArray:allsearchDictKeys];
[searchArray addObjectsFromArray:allsearchDictValues];

然后这样搜索:

 NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchText];
searchResults = [[searchArray filteredArrayUsingPredicate:resultPredicate] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

但是 table 视图 cell.textLabel 只显示值,而在 detailTextLabel 中不显示任何内容。那么我如何搜索字典的值和键,但保持单元格格式相同,其中键是 cell.textLabel,值是 cell.detailTextLabel

NSDictionary 允许您枚举它包含的键和值。你可以考虑这样的事情:

NSMutableArray *searchResults = [NSMutableArray alloc] init];
- (void)enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
    if ([key isEqualToString:searchText] || [obj isEqualToString:searchText] ) {
        [searchResults addObject:key];
}

现在您的搜索结果包含字典的键,键或对象与您的搜索字符串匹配。