简体   繁体   English

iOS核心数据按日期,月份年份汇总数据

[英]iOS core data sum data by date, month year

In iOS, I am trying to sum a core data field by day, month and year.I found some examples using NSExpression , but not this specific request. 在iOS中,我试图按日,月和年对核心数据字段进行求和。我发现了一些使用NSExpression示例,但没有此特定请求。

Here is my data object: 这是我的数据对象:

data{
  amount:NSNumber
  date:NSDate
}

Looking to group the data by day, month, and year then sum the amounts. 希望按日,月和年对数据进行分组,然后对金额求和。

Thanks. 谢谢。

You can have a transient attribute for the date components. 您可以为日期组件设置一个过渡属性。 You have to add these to the managed object model as transient and to the entity subclass. 您必须将它们作为临时对象添加到托管对象模型中,并添加到实体子类中。 They can be calculated like this: 可以这样计算:

-(NSNumber*)year {
   NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   NSDateComponents *comps = [greg components:NSYearCalendarUnit fromDate:self.date];
   return @(comps.year);
}

Do the equivalent with months and days by devising a scheme that captures the relevant parts of the date in some primitive numeric form, eg days: 通过设计一种以原始数字形式(例如,天)捕获日期相关部分的方案,对月份和日期进行等效处理:

-(NSNumber*)day {
   NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   NSDateComponents *comps = [greg 
      components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
      fromDate:self.date];
   return @(comps.year*10000+comps.month*100+comps.day);
}

( With the above scheme, that is really all you need. But having explicit year and month attributes will make your code more readable. ) 使用上述方案,这实际上是您所需要的。但是具有明确的yearmonth属性将使您的代码更具可读性。

Now to group in a NSFetchedResultsController you can have year or day as the sectionNameKeyPath . 我们在一组NSFetchedResultsController你可以有yeardaysectionNameKeyPath You can also group/filter with predicates like this: 您还可以使用以下谓词对分组/过滤:

NSArray *dataFor2000 = [allData filteredArrayUsingPredicate:
  [NSPredicate predicateWithFormat:@"year = %@", @2000]];

Calculating the sum is trivial with key paths: 使用关键路径计算总和是微不足道的:

NSNumber *sum = [dataFor2000 valueForKeyPath:@"@sum.amount"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM