在我的应用中,我按日期添加了一些交易。每个交易都有一个amount
字段,我想计算给定范围的所有交易的总和,比如当前周。
如何使用Core Data完成此操作?
我想到了两种方法:
Date
的范围并计算每次迭代的总和propertiesToGroupBy
propertiesToFetch
和NSFetchRequest
醇>
其中一种方法是否良好?或者还有其他方法吗?
答案 0 :(得分:0)
我设法做到了这样:
let amountExpr = NSExpression(forKeyPath: "amount")
let sumExpr = NSExpression(forFunction: "sum:", arguments: [amountExpr])
let sumDescr = NSExpressionDescription()
sumDescr.expression = sumExpr
sumDescr.name = "sumOfAmount"
sumDescr.expressionResultType = .doubleAttributeType
let dateExpr = NSExpression(forKeyPath: "date")
let dateDescr = NSExpressionDescription()
dateDescr.expression = dateExpr
dateDescr.name = "date"
dateDescr.expressionResultType = .dateAttributeType
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Transaction")
request.sortDescriptors = Transaction.defaultSortDescriptors
request.propertiesToFetch = [dateDescr, sumDescr]
request.propertiesToGroupBy = [dateDescr]
request.resultType = .dictionaryResultType
request.returnsObjectsAsFaults = false
request.predicate = Transaction.rangeOfDatesPredicate(dateRange: Date.week())
let results = try! context.fetch(request) as! [NSDictionary]
for value in results {
print(value)
}
现在value
将是一个字典,其中日期为关键字,sum为value。
注意 :为了完成这项工作,我必须为添加到Core Data的每个日期调整时间相同,否则每个日期都会有所不同
extension Date {
static func current() -> Date {
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day], from: Date())
components.hour = 00
components.minute = 00
components.second = 00
return calendar.date(from: components)!
}
}