搜索字典值&钥匙和钥匙在UITableView问题中显示

时间:2015-01-11 03:43:36

标签: ios nsdictionary uisearchdisplaycontroller

我正在尝试更新我的搜索显示控制器,但是现在,我已将其设置为:

 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;
}

并在表格视图中显示结果:

- (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:)];

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

1 个答案:

答案 0 :(得分:2)

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

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

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