开发者_Go百科I have a product search that searches the ProductCategories my products are in, sometimes my products are in multiple categories which gives me duplicate results. I don't want to search the product table directly because there are several products that have multiple sizes but are basically the same product.
Is there a way to get distinct search results with an NSFetchedResultsController?
Yes you can...
look out for the method
- (NSFetchedResultsController *)fetchedResultsController;
and add there the following lines (in this example we get only the distinct "title" attribute of our managed objects):
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"title"]];
self.fetchedResultsController.delegate = nil;
you have to take care how you access the values from the NSFetchedResultsController... For example in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
use the following code to access the data:
NSDictionary* title = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [title objectForKey:@"title"];
In addition to the solution which Shingoo provided, please don't forget to set the NSFetchedResultsController's delegate to nil in order to disable automatic updates, which won't work with NSDictionaryResultType and distinct values:
self.fetchedResultsController.delegate = nil;
You'd need to use a NSPredicate (See Predicate Programming Guide)
It's complex, but you can do it using a SUBQUERY
When creating your NSFetchRequest
you can use -setReturnsDistinctResults:
and set it to YES
.
精彩评论