Core Data to-many关系filterContentForSearchText与NSPredicate

时间:2013-12-28 16:58:24

标签: ios xcode uitableview core-data nspredicate

我有xcdatamodeld,如下所示: enter image description here

UISearchBar UITableView Scope- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{ [searchResults removeAllObjects]; if ([scope isEqualToString:@"Name"]){ NSString *matchString = [NSString stringWithFormat: @".*\\b%@.*",searchText]; NSString *predicateString = @"SELF.name MATCHES[cd] %@"; NSPredicate *predicate =[NSPredicate predicateWithFormat: predicateString, matchString]; searchResults = [NSMutableArray arrayWithArray:[[self.fetchedResultsController fetchedObjects] filteredArrayUsingPredicate:predicate]]; } if ([scope isEqualToString:@"Ingredient"]){ NSString *matchString = [NSString stringWithFormat: @".*\\b%@.*",searchText]; NSString *predicateString = @"ANY SELF.ingredients.name MATCHES[cd] %@"; NSPredicate *predicate =[NSPredicate predicateWithFormat: predicateString, matchString]; searchResults = [NSMutableArray arrayWithArray:[[self.fetchedResultsController fetchedObjects] filteredArrayUsingPredicate:predicate]]; } } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{ [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{ [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } - (void)viewDidLoad { searchResults = [NSMutableArray arrayWithCapacity:[[fetchedResultsController fetchedObjects] count]]; } 就是这样:

enter image description here

我添加了以下方法:

{{1}}

我想要的是什么:

(1)当我搜索带有“名称”范围的单词时,该应用会显示名称包含单词的所有食谱

enter image description here

(2)当我搜索带有“成分”范围的单词时,应用程序会显示所有含有名称包含单词

的成分的食谱

enter image description here

以上图片显示了两个名为“aglio olio pepe”和“rigatoni sale pepe”的食谱以及成分(aglio,olio,pepe)和(rigatoni,sale,pepe)。

第二次搜索应该显示两者。

实际起作用:(1)

实际上什么不起作用:(2)

WHY吗

1 个答案:

答案 0 :(得分:0)

更改xcdatamodeled解决了问题

enter image description here