开发者

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

开发者 https://www.devze.com 2023-03-26 07:24 出处:网络
开发者_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 t

开发者_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号