核心数据组按月和总和

是否有任何方式基于其月份的GROUP BY核心数据然后SUM其属性? 我有这样的数据

 ------------------------ date | amount ------------------------ 30-08-2017 | 124000000 28-10-2017 | 124000000 16-10-2017 | 124000000 14-12-2017 | 124000000 20-12-2017 | 124000000 ------------------------ 

我只需要显示一个最近的一年,所以我创build了我的提取请求

 NSDate *now = [NSDate date]; NSDate *oneYearAgo = [now addYears:-1]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyTable" inManagedObjectContext:moc]; [request setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(myDate >= %@) AND (myDate <= %@) AND isActive == %@", oneYearAgo, now, @YES]; [request setPredicate:predicate]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"myDate" ascending:YES]; [request setSortDescriptors:@[sort]]; NSExpressionDescription* ex = [[NSExpressionDescription alloc] init]; [ex setName:@"totalCost"]; [ex setExpression:[NSExpression expressionWithFormat:@"@sum.amount"]]; [ex setExpressionResultType:NSDecimalAttributeType]; [request setPropertiesToFetch:[NSArray arrayWithObjects:@"myDate", ex, nil]]; [request setPropertiesToGroupBy:[NSArray arrayWithObject:@"myDate"]]; [request setResultType:NSDictionaryResultType ]; NSArray *result = [moc executeFetchRequest:request error:nil]; 

这是我所需要的最接近的解决scheme,但是这个分组仍然是基于一天但是一个月,而不是它的总和。

所以我想要得到这样的结果

 Aug 2017 | 124000000 Oct 2017 | 248000000 Dec 2017 | 248000000 

任何帮助,将不胜感激。 谢谢!

您可以使用NSFetchResultsContoller自定义部分path来根据月份对数据进行分组。 然后,您可以将该部分中的所有项目相加以获得所需的结果。 以下代码片段可用于创build提取结果控制器

 NSFetchedResultsController *dateAmountFetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"monthIndex" cacheName:@"MyEntity"]; 

在您的DateAmount实体上创build一个名为“monthIndex”的新的瞬态属性。 然后在你的DateAmount类上创build一个方法 – (NSString *)monthIndex,返回正确的月份号string。 应该使用@“monthIndex”作为按照上面的代码片段获取结果控制器的部分名称键path。 在获取请求的sorting描述符中,使用键为@“monthIndex”的sorting描述符来sorting项目,因为这是NSFetchedResultsController的要求。