Вопрос

I'd like to do the following:

Select distinct department
From employees
Order By department

(The order by part is optional).

Employees contains Person objects, which have a name and a department property.

I've looked through a whole lot of questions like this, however it's not working for me. This is how I'm trying to do it:

AppDelegate *applicationDelegate = [[NSApplication sharedApplication] delegate];
NSManagedObjectContext *context = [applicationDelegate managedObjectContext];

NSEntityDescription *personEntity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.returnsDistinctResults = YES;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[personEntity propertiesByName] objectForKey:@"department"]];

NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
    ALog(@"%@",error);
} else {
    return result;
}

For the content of:

Name | Department
P1   | D1
P2   | D1
P3   | D2

The above code gives me an array of 3 NSDictionaries, like this:

{
    department = D1
}
{
    department = D1
}
{
    department = D2
}
Это было полезно?

Решение

To anyone who has the same problem:

What I found is that, if persistent store type is NSSQLiteStoreType the returnDistinctResults works. But for NSXMLStoreType distinct values are not working.

Credit to this answer.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top