gpt4 book ai didi

objective-c - NSFetchedResultsController 与搜索

转载 作者:太空狗 更新时间:2023-10-30 03:15:39 25 4
gpt4 key购买 nike

过滤 NSFetchedResultsController 数据的最佳实践是什么?每次搜索栏的文本更改时我都需要重新初始化它吗?

我正在使用 UISearchDisplayControllers 并且我正在实现:

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

谢谢。

最佳答案

Guy 的答案代码与问题有何不同?据我猜测,filterContentForSearchText:scope 方法是由 shouldReload 方法调用的?

无论如何,这是我在 CoreDataBooks 示例中添加的一些类似代码以包括搜索。在 IB 中为 CoreDataBooks 示例添加一个搜索显示 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;
}

附言。为了回答 Vivas,它使用 UISearchDisplayController 自动创建一个新的 TableView 来覆盖过滤后的列表。您可以检查正在使用哪个 tableView,如文档中所示,但在最简单的设置中它只是工作,因为 fetchedResultsController 要么在搜索的 TableView 中显示过滤版本,要么在 TableView 中显示所有数据。

关于objective-c - NSFetchedResultsController 与搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com