我正在尝试获取所有对象上属性的唯一值列表(类似于[array valueForKeyPath:@"@distinctUnionOfObjects.key"]
。据我所知,我应该能够通过创建NSFetchRequest
并将resultType
设置为NSDictionaryResultType
并指定propertiesToFetch
来完成此操作并将returnsDistinctResults
设置为YES
似乎不起作用。
我用三个属性Person
,firstName
和lastName
创建了一个名为age
的实体。这是我尝试使用的代码:
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);
当我运行它时,这是我得到的日志:
2017-10-12 16:17:54.723 TestCoreData[10650:879197] (
{
age = 18;
},
{
age = 18;
},
{
age = 18;
},
{
age = 18;
}
)
将
propertiesToFetch
更改为@[@"lastName"]
会得到类似的结果:2017-10-12 16:32:45.143 TestCoreData[10800:929908] (
{
lastName = Smith;
},
{
lastName = Johnson;
},
{
lastName = Johnson;
},
{
lastName = Smith;
}
)
我的期望是,这些只会为
age
返回一个条目,为lastName
返回两个条目。我误会了用法
的
returnsDistinctResults
或使用不正确? 最佳答案
事实证明,这是因为我使用的是内存中存储。如果我改用SQLite存储支持它,它可以按预期工作,并给出以下结果:
2017-10-12 17:21:48.546 TestCoreData[11767:1035544] (
{
age = 18;
}
)
和
2017-10-12 17:23:52.632 TestCoreData[11803:1044179] (
{
lastName = Johnson;
},
{
lastName = Smith;
}
)
我的猜测是,独特的功能是在查询语句中发生的,并不存在于针对内存存储区的提取中。