核心数据获取不同的属性值

时间:2014-05-15 08:44:28

标签: objective-c core-data nsfetchrequest

我想做以下事情:

Select distinct department
From employees
Order By department

(按部分的顺序是可选的)。

员工包含Person对象,它们具有名称和部门属性。

我已经查看了很多像这样的问题,但这对我不起作用。这就是我试图这样做的方式:

AppDelegate *applicationDelegate = [[NSApplication sharedApplication] delegate];
NSManagedObjectContext *context = [applicationDelegate managedObjectContext];

NSEntityDescription *personEntity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.returnsDistinctResults = YES;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[personEntity propertiesByName] objectForKey:@"department"]];

NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
    ALog(@"%@",error);
} else {
    return result;
}

内容:

Name | Department
P1   | D1
P2   | D1
P3   | D2

上面的代码给了我一个包含3个NSDictionaries的数组,如下所示:

{
    department = D1
}
{
    department = D1
}
{
    department = D2
}

1 个答案:

答案 0 :(得分:0)

对于遇到同样问题的人:

我发现,如果持久存储类型为NSSQLiteStoreType,则returnDistinctResults有效。但是对于NSXMLStoreType,不同的值不起作用。

Credit to this answer