【发布时间】:2016-07-27 07:16:17
【问题描述】:
我想要的是一个艺术家拥有的专辑的数量。所以我想使用分组依据。但我不想遍历所有艺术家并计算那里的专辑。
所以我想出了这个代码:
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;
}
)
这种获取方式是否仅适用于原始数据类型而不适用于对象关系?任何帮助表示赞赏!谢谢:)
【问题讨论】:
-
尝试计算相关实体的属性,而不是实体本身。例如,请参阅here。在您的情况下 count(artist.name),假设没有艺术家的名称为空。
-
将您的计数表达式基于某些属性——而不是关系——比如
title,并使用request.propertiesToFetch = @[@"artist", ex];
标签: objective-c object core-data group-by relationship