如何在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,所以也许有更好的和完全不同的方法来解决此问题?
最佳答案
我在这个问题中发现了类似的问题:
Sum of (double) fetch request field
我对代码做了一些修改,并提出了以下解决方案:
import SwiftUI
import CoreData
struct DashboardView: View {
@Environment(\.managedObjectContext) var managedObjectContext
// FetchRequest with predicate set to "after now"
@FetchRequest(entity: NPTransaction.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \NPTransaction.value, ascending: false)], predicate: NSPredicate(format: "date > %@", Date() as NSDate)) var fetchRequest: FetchedResults<NPTransaction>
// sum results using reduce
var sum: Int64 {
fetchRequest.reduce(0) { $0 + $1.value }
}
var body: some View {
NavigationView {
VStack(alignment: .leading) {
HStack {
VStack(alignment: .leading) {
Text("sum")
Text("\(sum)")
.font(.largeTitle)
}
Spacer()
}
.padding()
Spacer()
}.navigationBarTitle("Title")
}
}
}
struct DashboardView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return DashboardView().environment(\.managedObjectContext, context)
}
}
关于ios - 如何在SwiftUI中汇总过滤后的核心数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59681508/