我有一个带有实体“事件”的核心数据数据库和一个带有“日期”类型的属性“事件日期”。该任务显示按日期分组的事件,并按日期显示事件的数量(@“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;
}