Cocoa touch 核心数据:获取按多个属性分组的字典

Cocoa touch 核心数据:获取按多个属性分组的字典,cocoa-touch,core-data,Cocoa Touch,Core Data,我有一个NSManagedObject子类条目,其属性为类型(int)和日期(NSDate)。现在,我使用以下代码获取按类型分组的当前日期的条目 NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entry"]; [request setResultType:NSDictionaryResultType]; NSExpression *keyPathExpression = [NSExpression

我有一个NSManagedObject子类条目,其属性为类型(int)和日期(NSDate)。现在,我使用以下代码获取按类型分组的当前日期的条目

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entry"];
[request setResultType:NSDictionaryResultType];

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"type"];
NSExpression *countExpression = [NSExpression expressionForFunction:@"count:" arguments:@[keyPathExpression]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"entryCountByType"];
[expressionDescription setExpression:countExpression];
[expressionDescription setExpressionResultType:NSInteger64AttributeType];

[request setPropertiesToFetch:@[@"type",expressionDescription]];
[request setPropertiesToGroupBy:@[@"type"]];

[request setPredicate:[NSPredicate predicateWithFormat:@"date == %@", [NSDate date]]];

NSError *error;
NSArray *results = [defaultManagedObjectContext() executeFetchRequest:request error:&error];
一个条目类型为3,一个条目类型为5的一天的结果如下:

<_PFArray 0x15e05b50>(
{
    entryCountByType = 1;
    type = 3;
},
{
    entryCountByType = 1;
    type = 5;
}
)
按照我的想法,也就是说,通过一个获取请求,这可能吗?每天单独进行一次抓取(大约30次连续抓取)确实会减慢我的应用程序的速度。我曾尝试将@“date”添加到propertiesToGroupBy(当然,在删除日期谓词之后),但所做的只是将类似的结果返回到第一个输出,只需插入一个日期参数,以便将一天的每个类型拆分为单独的字典。

您将“day”和“date”混淆了
NSDate
精确到毫秒,因此您可能只有唯一的日期。不能按日期范围分组

一种方法是将一天存储为临时属性。该方案无关紧要,但有一种可能性,例如,
年*10000+月*100+天


如果您想省去
NSExpression
s,您可以在实体中使用一个返回日期字符串的方法
day
(使用
NSDateFormatter
)并使用
NSFetchedResultsController
day
作为
sectionNameKeyPath
来显示分组数据。

我已经通过使用NSDateComponents解决了这个问题,只保留所有nsDate的日/月/年,但感谢您的输入,让我们知道。您仍然可以投票支持此答案,以表示对您所做的努力的赞赏,因为它准确地解释了机制。我没有足够的声誉来投票支持,算了吧。在这种情况下,您可以随时接受它,因为此答案也捕获了您的解决方案(用您自己的数据方案替换
NSDate
)。但这并不能解决我的问题,抱歉,因为我每天仍然可以有多个条目,我需要在特定的一天获得所有条目的总数。
(
{
    date = 6/4/14 00:00:00;
    type1 = 2;
    type2 = 1;
},
{
    date = 6/5/14 00:00:00;
    type1 = 3;
    type2 = 2;
}
)