这是我的获取请求:
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)
}
但它会产生错误:
*由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'* - [__ NSArrayM insertObject:atIndex:]:object不能为nil'
为什么?
答案 0 :(得分:2)
设置NSExpressionDescription的名称。名称是将在字典中用于返回值的键。我已经更改了获取请求的结果类型,使其适用于Dictionary类型。
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)
}
}