2016-07-27 76 views
0

有以下几种与有关系的实体: Album <-> Artist relationship核心数据“组由”与给定的对象关系

我想是的相册艺术家有个数。所以我想用group by。但我不想遍历所有的艺术家,并计算专辑。

所以我想出了这个代码:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:objectStore.mainQueueManagedObjectContext]; 
[fetchRequest setEntity:entity]; 

NSExpressionDescription* ex = [[NSExpressionDescription alloc] init]; 
[ex setExpression:[NSExpression expressionWithFormat:@"count:(artist)"]]; 
[ex setName:@"count"]; 
[ex setExpressionResultType:NSDecimalAttributeType]; 

[fetchRequest setPropertiesToFetch:@[ @"artist", ex ]]; 
[fetchRequest setPropertiesToGroupBy:@[ @"artist" ]]; 
[fetchRequest setResultType:NSDictionaryResultType ]; 

id results = [objectStore.mainQueueManagedObjectContext executeFetchRequest:fetchRequest error:nil]; 

它返回以下结果:

<_PFArray 0x7fa1f34c4350>(
{ 
    artist = "0xd000000000080000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p2>"; 
    count = "0xd0000000000c0000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p3>"; 
}, 
{ 
    artist = "0xd000000000280000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p10>"; 
    count = "0xd000000000080000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p2>"; 
}, 
{ 
    artist = "0xd000000000300000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p12>"; 
    count = "0xd000000000380000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p14>"; 
}, 
{ 
    artist = "0xd000000000400000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p16>"; 
    count = "0xd000000000040000 <x-coredata://969B0BFF-9B87-4280-9B41-7920138902FC/Artist/p1>"; 
} 
) 

我期待不同的东西。当我使用releaseYear代替artist结果(如预期)是这样的:

<_PFArray 0x7f9f235e91c0>(
{ 
    count = 2; 
    releaseYear = 0; 
}, 
{ 
    count = 2; 
    releaseYear = 1983; 
}, 
{ 
    count = 1; 
    releaseYear = 1984; 
}, 
{ 
    count = 1; 
    releaseYear = 1985; 
} 
) 

请问这种只获取与原始数据类型工作,并且不与对象的关系?任何帮助表示赞赏!谢谢:)

+1

尝试统计相关实体的属性,而不是实体本身。例如,请参阅[这里](http://stackoverflow.com/a/27323977/3985749)。在你的案例中(artist.name),假设艺术家没有空名称。 – pbasdf

+1

将你的计数表达式基于某个属性 - 不是关系 - 如'title',并使用'request.propertiesToFetch = @ [@“artist”,ex];' – bteapot

回答

0

正如在评论中提到的,使用title解决了它。我的更新表达式如下所示:

NSExpressionDescription* ex = [[NSExpressionDescription alloc] init]; 
[ex setExpression:[NSExpression expressionWithFormat:@"count:(title)"]]; 
[ex setName:@"count"]; 
[ex setExpressionResultType:NSDecimalAttributeType];