0
有以下幾種與有關係的實體: 核心數據「組由」與給定的對象關係
我想是的相冊的藝術家有個數。所以我想用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;
}
)
請問這種只獲取與原始數據類型工作,並且不與對象的關係?任何幫助表示讚賞!謝謝:)
嘗試統計相關實體的屬性,而不是實體本身。例如,請參閱[這裏](http://stackoverflow.com/a/27323977/3985749)。在你的案例中(artist.name),假設藝術家沒有空名稱。 – pbasdf
將你的計數表達式基於某個屬性 - 不是關係 - 如'title',並使用'request.propertiesToFetch = @ [@「artist」,ex];' – bteapot