我可能会以错误的方式思考这个问题。
我有一个处理实体的搜索/过滤功能。但我希望能够过滤几个标准..
我有这个:
for (WordEntity *word in [self.fetchedResultsController fetchedObjects])
{
if ([scope isEqualToString:@"All"] || [word.greekText isEqualToString:searchText ])
{
NSComparisonResult result = [word.greekText compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.searchResults addObject:word];
}
}
但我希望过滤器捕获英文和希腊文字。我怎么做到最好?感谢
已更新
道歉,但我仍然无法让它发挥作用..我已经打开了它..
正如所建议的那样,我按如下方式更改了代码:
[self.searchResults removeAllObjects];
NSLog(@"predicating");
NSPredicate *englishTextPredicate = [NSPredicate predicateWithFormat:@"englishText CONTAINS[cd] %@", searchText];
NSLog(@"eng pred: %@", englishTextPredicate);
NSLog(@"search text: %@", searchText);
[self.fetchedResultsController.fetchRequest setPredicate:englishTextPredicate];
NSArray *fetchedData = [self.fetchedResultsController fetchedObjects];
self.searchResults = [fetchedData copy];
NSLog(@"search count: %i", self.searchResults.count);
但这会产生以下输出。
2014-08-03 07:31:40.846 GuessGreek[16535:425669] Card Count is: 651
2014-08-03 07:31:54.495 GuessGreek[16535:425669] -[WordViewController searchDisplayController:shouldReloadTableForSearchString:]
2014-08-03 07:31:54.495 GuessGreek[16535:425669] -[WordViewController filterContentForSearchText:scope:]
2014-08-03 07:31:54.496 GuessGreek[16535:425669] predicating
2014-08-03 07:31:54.496 GuessGreek[16535:425669] eng pred: englishText.text CONTAINS[cd] "o"
2014-08-03 07:31:54.496 GuessGreek[16535:425669] search text: o
2014-08-03 07:31:54.497 GuessGreek[16535:425669] search count: 651
这是单词的截图..显然,前两个单词没有" o"
我做错了什么?
答案 0 :(得分:2)
使用谓词会更简单。您可以使用复合谓词来搜索两件事。
NSPredicate * pred1 = [NSPredicate predicateWithFormat:@"greekText == %@", searchText];
NSPredicate * pred2 = [NSPredicate predicateWithFormat:@"englishText == %@", searchText];
NSPredicate * compPred = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:pred1,pred2,nil]];
[YourFetchRequestName setPredicate:compPred];
然后执行你的获取请求只能提供你想要的东西。
self.searchResults = [yourContext executeFetchRequest:YourFetchRequestName error:&error];
希望有所帮助!
答案 1 :(得分:0)
我发现一些效果很好的我认为:
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
[self.searchResults removeAllObjects];
NSLog(@"%s", __FUNCTION__);
for (WordEntity *word in [self.fetchedResultsController fetchedObjects])
{
NSRange greekResult = [word.greekText rangeOfString:searchText options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
NSRange englishResult = [word.englishText rangeOfString:searchText options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
if ( greekResult.location != NSNotFound || englishResult.location != NSNotFound ) {
[self.searchResults addObject:word];
}