使用Core Data检索唯一的结果集

时间:2010-04-16 21:34:39

标签: iphone cocoa core-data

我有一个基于核心数据的应用程序来管理一堆实体。我希望能够做到以下几点。

我有一个实体“SomeEntity”,其属性包括:name,type,rank,foo1,foo2。

现在,如果我们严格用SQL术语来说,SomeEntity有几行。我想要完成的是只检索可用的类型,即使每个实例都有重复的类型。我也需要他们按顺序返回。所以在SQL中,我正在寻找的是:

SELECT DISTINCT(type) ORDER BY rank ASC

这是我到目前为止的代码:

NSError *error = NULL;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"type", @"rank", nil]];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];

// sort by rank
NSSortDescriptor *rankDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rankDescriptor,nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[rankDescriptor release];

NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

[fetchRequest release];

return fetchResults;

现在崩溃的情况如下:Invalid keypath section passed to setPropertiesToFetch:

1 个答案:

答案 0 :(得分:17)

NSManagedObjectContext * ctx ; /* some ctx */    
NSFetchRequest * req; /* your request */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:context];
NSDictionary *entityProperties = [entity propertiesByName];
[req setEntity:entity];
[req setReturnsDistinctResults:YES];
[req setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"type"]]];
[req setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES]]];
NSArray * result = [ctx executeFetchRequest:req error:nil];