2016-07-05 46 views
-1

我已經實現了一個表視圖,它列出了來自核心數據實體的數據。我有大量存儲在Core Data中的數據(大約6000多條記錄 - 靜態數據)。現在我想用NSFetchedResultsController在表視圖中實現搜索。使用NSFetchedResultsController搜索核心數據實體記錄

我DB中的一列(屬性)有一個長字符串(用空格分隔)。我希望爲該句子中的每個單詞實施開始 - 如果單詞的其中一個詞開始於搜索詞,我的應用程序應列出db記錄。

例如,這裏是我的數據樣本:

記錄1 - 你好你好你好你怎麼樣 記錄2 - 嗨你好 記錄3 - 測試嗨

現在,如果我搜索「你好」 ,它應該列出Record-1和Record-2。

回答

0

您可以使用下面的代碼:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText]; 
[[_fetchedResultsController fetchRequest] setPredicate:predicate]; 
[[_fetchedResultsController fetchRequest] setFetchLimit:50]; 

或者,如果你會使用搜索結果控制器

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