如果您只想要所有不同航班代码的列表,这可能会满足您的需求:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flight"
inManagedObjectContext:moc];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entity.name];
request.resultType = NSDictionaryResultType;
request.returnsDistinctResults = YES;
request.propertiesToFetch = @[ entity.propertiesByName[@"flightCode"] ];
请注意,returnsDistinctResults
仅在propertiesToFetch
设置时才有效,并且propertiesToFetch
仅在resultType
is时才有效NSDictionaryResultType
。
修改
如果您想要完整Flight
的对象,但每个不同的航班代码只有一个,我认为您不能直接这样做。也许您可以同时要求对象 ID 和航班代码,按航班代码分组,并取最小对象 ID,以便为每个航班代码获取一个对象 ID。objectForID:
然后,您可以使用托管对象上下文将这些对象 ID 一一转换为完整对象。我会尝试这样的事情:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flight"
inManagedObjectContext:moc];
NSExpressionDescription *objectIDProperty = [[NSExpressionDescription alloc] init];
objectIDProperty.name = @"objectID";
objectIDProperty.expression = [NSExpression expressionForFunction:@"min:"
arguments:@[ [NSExpression expressedForEvaluatedObject] ]];
objectIdProperty.expressionResultType = NSObjectIDAttributeType;
NSAttributeDescription *flightCodeProperty = entity.propertiesByName[@"flightCode"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entity.name];
request.resultType = NSDictionaryResultType;
request.returnsDistinctResults = YES;
request.propertiesToFetch = @[ flightCodeProperty, objectIDProperty ];
request.propertiesToGroupBy = @[ flightCodeProperty ];
我从这个答案中抄袭了很多。我不知道它是否有效,或者我是否在正确的轨道上。如果它完全运行,但没有给出正确的输出,请记住,您可以通过添加-com.apple.CoreData.SQLDebug 1
命令行参数来查看它正在执行的 SQL。