我试图在我的所有对象上获取属性的唯一值列表(类似于[array valueForKeyPath:@"@distinctUnionOfObjects.key"]
。从我所知道的,我应该能够通过创建{{1}来实现这一点。将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
或使用不正确?
答案 0 :(得分:1)
事实证明这是因为我正在使用内存存储。如果我用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;
}
)
我的猜测是,不同的功能是在查询语句中发生的,并且对于内存存储中的提取不存在。