How to Search Array of Dictionary and show in UITableview?

。_饼干妹妹 提交于 2019-12-05 16:01:10

You need to modify your predicate to add the key to look for:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pname == %@", searchText];

Additionally == will actually look for exact matches, ie if you'll enter Band Camp T-Shirt as search then you'll get the result, you won't be able to get any result if you simply enter Band or Camp or Shirt. So in order to achieve the character based search, you need to modify predicate to include contain keyword.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pname contains[cd] %@", searchText];

[cd] will match with case insensitive.

My friend solve this issue. Here, is the code:

- (void) searchBarDidBeginEditing:(UISearchBar*) lclSearchBar
{
    self.searchBar.showsCancelButton = YES;
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{

    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    if (searchResults.count != 0) {
        [searchResults removeAllObjects];
    }
    for (int i=0; i< [self.arrProductList count]; i++)
    {
        NSString *string = [[self.arrProductList objectAtIndex:i] valueForKey:@"pname"];
        NSRange rangeValue = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (rangeValue.length > 0)
        {
            NSLog(@"string contains bla!");

            [searchResults addObject:[self.arrProductList objectAtIndex:i]];
        }
        else
        {
            NSLog(@"string does not contain bla");
        }
    }
    NSLog(@"fiilterArray : %@",searchResults);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!