如何是蓋伊的答案代碼問題有什麼不同?據我猜測,filterContentForSearchText:scope方法是由shouldReload方法調用的?
無論如何,下面是我在CoreDataBooks示例中添加的一些類似代碼,以包含搜索。 CoreDataBooks示例在IB中添加Search Display Controller。然後我將代碼添加到RootViewController.m中,如下所示:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
NSInteger searchOption = controller.searchBar.selectedScopeButtonIndex;
return [self searchDisplayController:controller shouldReloadTableForSearchString:searchString searchScope:searchOption];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
NSString* searchString = controller.searchBar.text;
return [self searchDisplayController:controller shouldReloadTableForSearchString:searchString searchScope:searchOption];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString*)searchString searchScope:(NSInteger)searchOption {
NSPredicate *predicate = nil;
if ([searchString length])
if (searchOption == 0) // full text, in my implementation. Other scope button titles are "Author", "Title"
predicate = [NSPredicate predicateWithFormat:@"title contains[cd] %@ OR author contains[cd] %@", searchString, searchString];
else
// docs say keys are case insensitive, but apparently not so.
predicate = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", [[controller.searchBar.scopeButtonTitles objectAtIndex:searchOption] lowercaseString], searchString];
[fetchedResultsController.fetchRequest setPredicate:predicate];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return YES;
}
PS。要使用UISearchDisplayController來回答Vivas,它會自動創建一個新的表格視圖,用於覆蓋已過濾的列表。您可以按照文檔中所示檢查正在使用哪個tableView,但是在最簡單的設置中,它可以正常工作,因爲fetchedResultsController在搜索的表視圖中顯示過濾版本或顯示錶視圖中的所有數據。
你是如何最終處理表視圖數據源方法,以便表視圖將知道是否顯示「過濾列表」? – CraigH 2009-10-06 20:37:47
這裏的答案是非常有幫助的 http://stackoverflow.com/questions/4471289/how-to-filter-nsfetchedresultscontroller-coredata-with-uisearchdisplaycontroll/4481896#4481896 – acecapades 2012-02-20 09:13:01
以下是我所做的:http:// stackoverflow .com/questions/4471289/how-to-filter-nsfetchedresultscontroller-coredata -with-uisearchdisplaycontrolle/4856118#4856118 – 2011-01-31 22:06:55