核心数据" group by"与对象的关系

时间:2016-07-27 07:16:18

标签: objective-c object core-data group-by relationship

以下是与之有关系的实体: 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 个答案:

答案 0 :(得分:0)

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

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