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

时间:2015-06-05 18:00:14

标签: cocoa-touch core-data

我有一个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个类型和1个输入类型5的结果是:

<_PFArray 0x15e05b50>(
{
    entryCountByType = 1;
    type = 3;
},
{
    entryCountByType = 1;
    type = 5;
}
)

我想要在没有日期谓词的情况下获取并按日期列出的每种类型都有计数(其中1天有2个类型1和1个类型2,另一天有3个类型1和2类型2):

(
{
    date = 6/4/14 00:00:00;
    type1 = 2;
    type2 = 1;
},
{
    date = 6/5/14 00:00:00;
    type1 = 3;
    type2 = 2;
}
)

这是否可能以我正在思考的方式,即使用单个获取请求?单独进行每天获取(大约30次连续提取)实际上是在减慢我的应用程序。我已经尝试将@“date”添加到propertiesToGroupBy(当然,在删除日期谓词之后),但所有这一切都会返回与第一个输出相似的结果,只是抛出一个日期参数,以便每天的每个类型都是分成单独的词典。

1 个答案:

答案 0 :(得分:0)

你混淆了“日”和“约会”。 NSDate精确到毫秒级,因此您可能只有唯一的日期。您无法按日期范围进行分组。

一种方法是将日期存储为瞬态属性。该方案无关紧要,但有一种可能性,例如year * 10000 + month * 100 + day

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

相关问题