如何在此表格视图中搜索结果?

时间:2013-01-19 16:20:03

标签: ios tableview uisearchbar

我希望能够在表格视图中添加搜索功能。该表列出了各种商店位置。我希望用户能够按城市进行过滤。我一直在考虑以某种方式添加下拉列表,可能在tableviewcell中创建过滤器。有谁做过这个可以帮助我的人吗?

我在表格视图中已经有一个搜索栏控件,但它只搜索记录的一个字段。如何确定或选择搜索栏在我的数据中实际查找的字段?这是我的代码:

#pragma mark Content Filtering

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {

    // Update the filtered array based on the search text and scope.

    // Remove all objects from the filtered search array

    [self.filteredResultsArray removeAllObjects];

    // Filter the array using NSPredicate

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];

    [self.filteredResultsArray = [NSMutableArray arrayWithArray:[self.dates filteredArrayUsingPredicate:predicate]] retain];

}



#pragma mark - UISearchDisplayController Delegate Methods

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {

    // Tells the table data source to reload when text changes

    [self filterContentForSearchText:searchString scope:

     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    // Return YES to cause the search result table view to be reloaded.

    return YES;

}



-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {

    // Tells the table data source to reload when scope bar selection changes

    [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:

     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

    // Return YES to cause the search result table view to be reloaded.

    return YES;

}

我的self.dates数组的填充方式如下:

- (void)loadRecordsFromCoreData {

    [self.managedObjectContext performBlockAndWait:^{

        [self.managedObjectContext reset];

        NSError *error = nil;

        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:self.entityName];

        [request setSortDescriptors:[NSArray arrayWithObject:

                                     [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]]];

        self.dates = [self.managedObjectContext executeFetchRequest:request error:&error];



    }];

}

是否与initWithEntityName ...

有关

1 个答案:

答案 0 :(得分:0)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];

该谓词确定在您的数据中搜索哪个字段 - 在这种情况下为名称字段。如果要搜索其他字段,只需将SELF.name更改为SELF.city或其他字段。如果您要搜索多个字段或在过滤器中使用其他逻辑,请查看Apple's NSPredicate Programming Guide