1

我有一个带有实体“事件”的核心数据数据库和一个带有“日期”类型的属性“事件日期”。该任务显示按日期分组的事件,并按日期显示事件的数量(@“count”)。例如 eventDate (mm-dd-yyyy) 数据:

events     eventDate
event 1    01-01-2013
event 2    01-01-2013
event 3    01-02-2013
event 4    01-03-2013
...

表格视图中的结果:

date         count
01-01-2013     2
01-02-2013     1
01-03-2013     1
...

不喜欢获取所有数据库,因为它可能很大,所以我使用聚合操作而不是获取每个对象。代码正常工作,但结果数组为空。我猜问题是日期类型属性和 NSAttribute/attributeType 的分组,但无法使其工作。事件的类别文件中的代码是:

+ (NSArray *)aggregateOperationOnEvent:(NSString *)attributeName withFunction:(NSString *)function withPredicate:(NSPredicate *)predicate inManagedObjectContext: (NSManagedObjectContext*)context {

NSEntityDescription* entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];

NSAttributeDescription* attributeDesc = [entity.attributesByName objectForKey:attributeName];


NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: attributeName];
NSExpression *functionExpression = [NSExpression expressionForFunction: [NSString stringWithFormat:@"%@:", function] arguments: [NSArray arrayWithObject:keyPathExpression]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: function];
[expressionDescription setExpression: functionExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];


NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];

[request setPropertiesToFetch:[NSArray arrayWithObjects:attributeDesc, expressionDescription, nil]];
[request setPropertiesToGroupBy:[NSArray arrayWithObject:attributeDesc]];
[request setResultType:NSDictionaryResultType];

if (predicate != nil)
    [request setPredicate:predicate];

NSError* error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

return results;

}

4

2 回答 2

0

聚合 aNSDate不是一个好主意,因为它是由浮点类型支持的。如果您将自参考日期以来的天数存储为int32_t. 您需要使用NSDateComponents

@implementation NSDate (Days)

-  (NSInteger)daysSinceReferenceDate;
{
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comp = [cal components:NSDayCalendarUnit fromDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0] toDate:self options:0];
    return [comp day];
}

@end
于 2013-02-12T20:02:04.560 回答
0

唯一的问题是当我将“结果”数组转移到另一个数组时,后者的分配代码不小心被注释掉了,这就是为什么我在 NSLog 中得到空数组的原因。所以好消息可以对 DATE 属性使用聚合操作,解决方案在上面。“结果”数组的打印输出:

 2013-02-13 19:19:48.063 YourAppsName[35147:c07] -------- results = (
    {
    count = 2;
    eventDate = "2013-01-01 00:00:00 +0000";
},
    {
    count = 1;
    eventDate = "2013-01-02 00:00:00 +0000";
},
    {
    count = 1;
    eventDate = "2013-01-03 00:00:00 +0000";
}

)

于 2013-02-13T14:27:36.657 回答