如何在SwiftUI应用程序中汇总过滤后的核心数据值(使用谓词?
我有1个名为NPTransaction的实体。它有5个属性,我想对名为value(Integer 64)的属性的值求和。基本上,它将汇总所选月份的收入值(现在在示例代码中将其设置为当前Date(),但稍后将其设置为整个当月)。
我发现了有关Swift的类似问题,但无法使此代码在我的应用中正常工作。链接到相关问题:How to sum the numbers(Int16) of stored core data - Swift 3
基于链接中的代码,我现在有以下代码:
import SwiftUI
struct DashboardView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@State var selectedDate = Date()
// This code in private var below produces many errors like:
// Value of type 'AppDelegate' has no member 'managedObjectContext'
// Use of undeclared type 'NSEntityDescription'
// Use of undeclared type 'NSFetchRequest'
// - so I assume that this linked question may be outdated or I should take different approach using SwiftUI
private var income: Int64 {
let context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
let entityDesc: NSEntityDescription = NSEntityDescription.entity(forEntityName: "NPTransaction", in: context)!
let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
request.entity = entityDesc
request.predicate = NSPredicate(format: "date == %@", selectedDate)
let records = try! context.fetch(request)
try! context.fetch(request) as! [NSManagedObject]
let monthlyIncome = result.reduce(0) { $0 + ($1.value(forKey: "value") as? Int64 ?? 0) }
return monthlyIncome
}
var body: some View {
NavigationView {
VStack {
Text("Monthly income:")
Text("\(income) USD")
}
// more code...
我只是在学习Swift和SwiftUI,所以也许有更好和完全不同的方式来解决此问题?
这应该解决您当前的代码,您正尝试减少称为result
的不存在的变量,我相信您是从链接的代码中获得的。您还将进行两次不必要的提取。希望这会有所帮助。
request.predicate = NSPredicate(format: "date == %@", selectedDate)
let records = try! context.fetch(request) as! [NSManagedObject]
let monthlyIncome = records.reduce(0) { $0 + ($1.value(forKey: "value") as? Int64 ?? 0) }
return monthlyIncome
此外,您可以通过NSFetchRequest和NSExpression对CoreData中的值求和。这是我在本文中找到的示例:Group by, Count and Sum in CoreData
let keypathExp1 = NSExpression(forKeyPath: "col")
let expression = NSExpression(forFunction: "sum:", arguments: [keypathExp1])
let sumDesc = NSExpressionDescription()
sumDesc.expression = expression
sumDesc.name = "sum"
sumDesc.expressionResultType = .integer64AttributeType
let request = NSFetchRequest(entityName: "Record")
request.returnsObjectsAsFaults = false
request.propertiesToFetch = [sumDesc]
request.resultType = .dictionaryResultType