核心数据:是否可以在分组中使用自定义功能

Cen*_*ion 8 sqlite iphone core-data objective-c

在objective-c中制作NSFetchRequest时,是否可以逐个使用自定义函数(strftime)?sql语句在sqlite中完全有效:

select date, count(*) from note group by strftime('%Y%m%d', date)
Run Code Online (Sandbox Code Playgroud)

然而,在经过一天的挖掘和尝试各种方法和解决方案之后,我得出结论,在单个sql fetch中使用核心数据是不可能的.我正在使用带有setPropertiesToGroupBy的NSFetchRequest(仅限iOS 5.0).

UPDATE.有一个例子可以通过apple提供核心数据来获取此类行为.但是,我已启用"-com.apple.CoreData.SQLDebug 1"来显示由核心数据执行的SQL.看来,核心数据没有执行我想要的SQL.它只是通过第一个SQL查询选择它们,然后遍历执行多个"SELEC .. WHERE ID IN ...."SQL查询的组.控制台的摘录:

2012-07-05 10:34:57.244 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK     FROM ZEVENT t0 ORDER BY t0.ZTIMESTAMP
2012-07-05 10:34:57.245 DateSectionTitles[1139:fb03] CoreData: annotation: sql   connection fetch time: 0.0010s
2012-07-05 10:34:57.246 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch    execution time: 0.0015s for 52 rows.
2012-07-05 10:34:57.247 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTIMESTAMP, t0.ZTITLE FROM ZEVENT t0 WHERE  t0.Z_PK IN  (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)  ORDER BY t0.ZTIMESTAMP LIMIT 20
2012-07-05 10:34:57.248 DateSectionTitles[1139:fb03] CoreData: annotation: sql connection fetch time: 0.0012s
2012-07-05 10:34:57.249 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch execution time: 0.0022s for 20 rows.
2012-07-05 10:34:57.250 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTIMESTAMP, t0.ZTITLE FROM ZEVENT t0 WHERE  t0.Z_PK IN  (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)  ORDER BY t0.ZTIMESTAMP LIMIT 20
2012-07-05 10:34:57.281 DateSectionTitles[1139:fb03] CoreData: annotation: sql connection fetch time: 0.0303s
2012-07-05 10:34:57.281 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch execution time: 0.0310s for 20 rows.
Run Code Online (Sandbox Code Playgroud)

Ola*_*laf 4

是的你可以。组装你的NSFetchedResultsController类似:

  NSFetchedResultsController *aFetchedResultsController =
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
  managedObjectContext:someManagedObjectContext
  sectionNameKeyPath:@"yearOnly" // <== 
  cacheName:@"cacheAsneeded"];
Run Code Online (Sandbox Code Playgroud)

然后在你的 NSManagedObject 类中添加一个要使用的方法sectionNameKeyPath

- (int)yearOnly { // 
   NSCalendar *cal = [NSCalendar currentCalendar];
   return [[cal components:NSYearCalendarUnit fromDate:self.date] year];
}
Run Code Online (Sandbox Code Playgroud)

该请求将返回按年份分组的结果,以便遇到的每个年份都将成为一个部分。

如果您也需要按月分组,您可能需要适当更改日历组件。

对于 count(*),将其添加NSExpression到您的 fetchRequest 中:

 NSExpression * many = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"someAttribute"]]];
Run Code Online (Sandbox Code Playgroud)