2013-01-19 50 views
0

我想能夠添加一個搜索功能到我的表格視圖。該表列出了各種商店位置。我希望用戶能夠按城市過濾。我一直在考慮以某種方式添加下拉列表,也許在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做...

回答

0

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

那謂詞確定在數據中搜索哪個字段 - 在這種情況下是名稱字段。如果你想搜索不同的領域,只需將SELF.name改爲SELF.city或其他字段。如果您想搜索多個字段或在過濾器中使用其他邏輯,請查看Apple's NSPredicate Programming Guide

+0

其實我需要搜索實體名稱和實體描述,所以我只是加了 - || SELF.description包含[c]%@「,searchText - 我解決了我的問題...... thx – marciokoko