I am attempting to get the a list of unique values for a property on all of my objects (similar to [array valueForKeyPath:@"@distinctUnionOfObjects.key"]
. From what I can tell, I should be able to accomplish this by creating an NSFetchRequest
with resultType
set to NSDictionaryResultType
, specifying the propertiesToFetch
and setting returnsDistinctResults
to YES
. Doing this does not seem to work.
I have created an entity called Person
with the three attributes firstName
, lastName
and age
. Here is the code I am trying to test this with:
NSManagedObjectModel *objectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objectModel];
[coordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
context.persistentStoreCoordinator = coordinator;
[context performBlockAndWait:^{
NSArray *lastNames = @[@"Smith",@"Johnson"];
NSArray *firstNames = @[@"John", @"Susan"];
for (NSString *lastName in lastNames) {
for (NSString *firstName in firstNames) {
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
person.firstName = firstName;
person.lastName = lastName;
person.age = @(18);
}
}
}];
[context save:nil];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = @[@"age"];
fetchRequest.returnsDistinctResults = YES;
NSArray *results = [context executeFetchRequest:fetchRequest error:nil];
NSLog(@"%@",results.description);
When I run this, this is the log I get:
2017-10-12 16:17:54.723 TestCoreData[10650:879197] (
{
age = 18;
},
{
age = 18;
},
{
age = 18;
},
{
age = 18;
}
)
Changing propertiesToFetch
to @[@"lastName"]
gives similar results:
2017-10-12 16:32:45.143 TestCoreData[10800:929908] (
{
lastName = Smith;
},
{
lastName = Johnson;
},
{
lastName = Johnson;
},
{
lastName = Smith;
}
)
My expectation would be that these would only return a single entry for age
and two for lastName
.
Am I misunderstanding the use
of returnsDistinctResults
or using it incorrectly?