NSFetchRequest with distinct properties

Rui Lopes picture Rui Lopes · Oct 8, 2011 · Viewed 7.9k times · Source

I'm trying to get a distinct result from NSPredicate.

My code:

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Members" inManagedObjectContext:context];
    request.entity = entity;
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"city"
                                                                                     ascending:YES
                                                                                      selector:@selector(caseInsensitiveCompare:)]];

    request.predicate = [NSPredicate predicateWithFormat:@"memberDeleted == %@", [NSNumber numberWithBool:NO]];

    NSDictionary *properties = [entity propertiesByName];
    request.propertiesToFetch = [NSArray arrayWithObject:[properties objectForKey:@"city"]];
    request.returnsDistinctResults = YES;

    request.fetchBatchSize = 20;

    NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                          managedObjectContext:context
                                                                            sectionNameKeyPath:nil
                                                                                     cacheName:@"CityCache"];
    [request release];

    self.fetchedResultsController = frc;
    [frc release];

The issue is that the result returns many times the same City. This Entity has a lot of Members, and each Member has a property "city".

What am I doing wrong?

Thanks,

RL

Answer

Alex picture Alex · Oct 8, 2011

Make sure to set the resultType of the NSFetchRequest to NSDictionaryResultType. The default is to return the actual objects, and so it will ignore propertiesToFetch.