CoreData 查询小记

CoreData 如果要进行条件查询,一般使用

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = 2"];

但是现在有这样一个需求:
CoreData的数据表:字段如下

name:
date:
.....

其中date为保存数据时存入的日期,现在要对时间归纳,统计出日期为同一天的数据有几组?
2020-01-10有10个
2010-02-09有3个
由于我们并不知道具体的日期,所以无法通过NSPredicate查找,在Excel中其实很容易办到,在代码中这时候我们需要用到NSExpression
它包含了强大的数学计算

1、统计:
     average:
     sum:
     count:
     min:
     max:
     median:
     mode:
     stddev:
     2、基本运算:
     add:to:
     from:subtract:
     multiply:by:
     divide:by:
     modulus:by:
     abs:
     3、高级运算
     sqrt:
     log:
     ln:
     raise:toPower:
     exp:

解决刚才的需求

let expressionDescreption = NSExpressionDescription()
//采用的是计数运算,所以需要设定一个字段对应的出来的value
        expressionDescreption.name = "headCount"
//设定计算方式为count,并且还要设置需要计算的字段,这里日期用的是remdate字段
        expressionDescreption.expression = NSExpression(forFunction: "count:",arguments: [NSExpression(forKeyPath: "remdate")])
//设置接收的key
        fetchRequest.propertiesToFetch = ["remdate", expressionDescreption]
        fetchRequest.propertiesToGroupBy = ["remdate"]
        expressionDescreption.expressionResultType = .undefinedAttributeType
        fetchRequest.resultType = .dictionaryResultType
let fetchResults = try managedObectContext.fetch(fetchRequest)

最终打印结果为

[{
    headCount = 3;
    remdate = "2010-05-10";
}, {
    headCount = 1;
    remdate = "2010-05-11";
}, {
    headCount = 1;
    remdate = "2010-05-15";
}]

计算出总共有三天,每一天总共有多少个数据。

你可能感兴趣的:(CoreData 查询小记)