Search code examples
iosobjective-ccore-datansfetchedresultscontrollernsfetchrequest

NSFetchRequest Distinct with Change Track


I am using NSFetchRequest to return data from Core Data, My issue is that I have multiple objects being returned with the same Unique key which I would like to group together to display one cell per unique value in my Table View. I understand that it is not possible to use setReturnsDistinctResults:YES and preserve 'Change Track'

The aim of all this is to display a list of messages which are grouped by the mesg_conv_unique value. Which a user can then select to go to the message board view I have setup. This is done by parsing the unique key to the view, which is working fine.

My code thus far.

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"message"
                                          inManagedObjectContext:self.managedObjectContext];


[request setEntity:entity];
[request setFetchBatchSize:100];
[request setPredicate:nil];
[request setReturnsDistinctResults:YES];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:@[@"mesg_conv_unique"]];

Can anyone suggest a way to do this whilst still preserving 'Change Track' or perhaps another method by which I can achieve my goal?


Solution

  • The solution was to use sections here:

    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                                                   managedObjectContext:self.managedObjectContext
                                                                                                     sectionNameKeyPath:@"mesg_conv_unique"
                                                                                                              cacheName:nil];
    

    And in the…

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 1;
        id items = [self.fetchedResultsController.sections objectAtIndex:section];
        return [items numberOfObjects];
    }