【发布时间】:2012-01-18 15:37:40
【问题描述】:
使用 NSPredicate 结合 tableview 和 NSFetchedResultsController 上的搜索框的非常奇怪的结果
它应该基于匹配的名称进行过滤...但是,如果我输入任何有效的名称,我会得到一些不正确的结果。如果我输入任何全名,例如“Mike Johnson”或“Kelly Michaels”,我总是会得到与“Angelo Smith”相同的过滤结果。
NSLog 将显示 "名称包含[cd] \"Kelly Michaels\""
但是屏幕上显示的过滤结果只会显示 Angelo Smith?任何想法如何解决这个问题?
如果您需要有关我正在做的事情的更多详细信息,我一直在使用此堆栈帖子中的解决方案 How to filter NSFetchedResultsController (CoreData) with UISearchDisplayController/UISearchBar
- (NSFetchedResultsController *)newFetchedResultsControllerWithSearch:(NSString *)searchString
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
NSPredicate *filterPredicate = nil;
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Staff" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSMutableArray *predicateArray = [NSMutableArray array];
if(searchString.length)
{
NSLog(@"here searchString is %@", searchString);
// your search predicate(s) are added to this array
[predicateArray addObject:[NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchString]];
// finally add the filter predicate for this view
NSLog(@"%@", predicateArray);
if(filterPredicate)
{
filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:filterPredicate, [NSCompoundPredicate orPredicateWithSubpredicates:predicateArray], nil]];
}
else
{
filterPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicateArray];
}
}
[fetchRequest setPredicate:filterPredicate];
...
【问题讨论】:
-
嗯,它似乎返回了正确数量的结果。即,如果我输入“Mar”,我会得到两个结果。这是有道理的,因为我有两个名字中带有“Mar”的员工。马克和玛丽。然而,名字改为“Angelo”和“Colin”。所以它过滤了正确数量的员工,只是没有显示他们的正确姓名?我需要某个地方的 reloadData 吗?
标签: objective-c ios core-data uisearchbar