如何执行 fetch 请求以获取带有表达式描述的参数之和?

How to perform fetch request to get the sum of parameter with expression description?

这是我的提取请求:

    let request = NSFetchRequest<Service>()
    let sorter = NSSortDescriptor(key: "date", ascending: true)

    let entity = NSEntityDescription()
    entity.name = "Service"
    request.entity = entity
    request.sortDescriptors = [sorter]
    request.resultType = .dictionaryResultType
    request.predicate = NSPredicate(format: "month.identifier = 201703")

    let exp = NSExpressionDescription()
    exp.expression = NSExpression(forKeyPath: "@sum.duration")
    exp.expressionResultType = .integer64AttributeType
    request.propertiesToFetch = [exp]

    do {
        let result = try NSManagedObjectContext.mr_default().fetch(request) //error is here
        print("+++++ \(result)")
    } catch {
        print(error)
    }

但是它产生了一个错误:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

为什么?

设置 NSExpressionDescription 的名称。该名称是将在字典中用于 return 值的键。我更改了获取请求的结果类型,使其适用于字典类型。

    let request = NSFetchRequest<NSFetchRequestResult>()
    let sorter = NSSortDescriptor(key: "date", ascending: true)

    let entity = NSEntityDescription()
    entity.name = "Service"
    request.entity = entity
    request.sortDescriptors = [sorter]
    request.resultType = .dictionaryResultType
    request.predicate = NSPredicate(format: "month.identifier = 201703")

    let exp = NSExpressionDescription()
    exp.name = "sumOfduration"
    exp.expression = NSExpression(forKeyPath: "@sum.duration")
    exp.expressionResultType = . integer64AttributeType
    request.propertiesToFetch = [exp]

    do {
        let result = try UMUserDBManager.sharedInstance.getThreadManagedObjectContext().fetch(request) //error is here
        print("+++++ \(result)")
    } catch {
        print(error)
    }

}