Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to get distinct results when using an NSFetchedResultsController?

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?

like image 923
Slee Avatar asked Aug 08 '11 00:08

Slee


2 Answers

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"];
like image 88
Shingoo Avatar answered Sep 18 '22 16:09

Shingoo


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; 
like image 25
AlexR Avatar answered Sep 20 '22 16:09

AlexR