我有一个产品搜索,用于搜索我的产品所在的ProductCategories,有时我的产品有多个类别,这些类别给了我重复的结果。我不想直接搜索产品表,因为有几种产品具有多种尺寸,但基本上是相同的产品。使用NSFetchedResultsController时可能会得到不同的结果吗?
有没有办法用NSFetchedResultsController获得不同的搜索结果?
我有一个产品搜索,用于搜索我的产品所在的ProductCategories,有时我的产品有多个类别,这些类别给了我重复的结果。我不想直接搜索产品表,因为有几种产品具有多种尺寸,但基本上是相同的产品。使用NSFetchedResultsController时可能会得到不同的结果吗?
有没有办法用NSFetchedResultsController获得不同的搜索结果?
是的,你可以...
寻找出方法
- (NSFetchedResultsController *)fetchedResultsController;
,并添加有以下行(在这个例子中,我们只获得了独特的“标题”我们的管理对象的属性) :
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"title"]];
self.fetchedResultsController.delegate = nil;
你有你如何访问从NSFetchedResultsController值来照顾......例如,在
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
使用下面的代码来访问数据:
NSDictionary* title = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [title objectForKey:@"title"];
你需要使用一个NSPredicate(见Predicate Programming Guide)
这是复杂的,但你可以使用子查询
在创建NSFetchRequest
可以使用-setReturnsDistinctResults:
并将其设置为YES
做到这一点。
使用,你还必须设置setResultType:NSDictionaryResultType NSFetchedResultsController不喜欢 – Slee
@Slee:更确切地说:FRC不支持NSDictionaryResultType。 –
除提供Shingoo提供的解决方案,请不要忘记设置的NSFetchedResultsController的委托零为了禁用自动更新,这将无法与NSDictionaryResultType和不同的值:
self.fetchedResultsController.delegate = nil;
ferdil - 你能详细说明你的答案吗? – NSPratik