title: Core Data fetch distinct values of property
body: <p>I'd like to do the following:</p>
  
  <pre><code>Select distinct department
  From employees
  Order By department
  </code></pre>
  
  <p>(The order by part is optional).</p>
  
  <p>Employees contains Person objects, which have a name and a department property.</p>
  
  <p>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:</p>
  
  <pre><code>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:&amp;error];
  if (error) {
      ALog(@"%@",error);
  } else {
      return result;
  }
  </code></pre>
  
  <p>For the content of:</p>
  
  <pre><code>Name | Department
  P1   | D1
  P2   | D1
  P3   | D2
  </code></pre>
  
  <p>The above code gives me an array of 3 NSDictionaries, like this:</p>
  
  <pre><code>{
      department = D1
  }
  {
      department = D1
  }
  {
      department = D2
  }
  </code></pre>