【发布时间】:2011-10-22 01:12:05
【问题描述】:
我有一个产品搜索来搜索我的产品所在的 ProductCategories,有时我的产品属于多个类别,这给了我重复的结果。我不想直接搜索产品表,因为有几个产品有多种尺寸但基本上是相同的产品。
有没有办法使用 NSFetchedResultsController 获得不同的搜索结果?
【问题讨论】:
标签: objective-c iphone core-data nsfetchedresultscontroller
我有一个产品搜索来搜索我的产品所在的 ProductCategories,有时我的产品属于多个类别,这给了我重复的结果。我不想直接搜索产品表,因为有几个产品有多种尺寸但基本上是相同的产品。
有没有办法使用 NSFetchedResultsController 获得不同的搜索结果?
【问题讨论】:
标签: objective-c iphone core-data nsfetchedresultscontroller
您需要使用 NSPredicate(请参阅 Predicate Programming Guide)
这很复杂,但您可以使用 SUBQUERY 来完成
【讨论】:
创建NSFetchRequest 时,您可以使用-setReturnsDistinctResults: 并将其设置为YES。
【讨论】:
是的,你可以...
注意方法
- (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"];
【讨论】:
除了Shinoo提供的解决方案之外,请不要忘记设置 NSFetchedResultsController's delegate to nil 以禁用自动更新,这不适用于 NSDictionaryResultType 和不同的值:
self.fetchedResultsController.delegate = nil;
【讨论】: