如何在SwiftUI中汇总过滤后的核心数据? [英] How to sum filtered Core Data in SwiftUI?

查看:92
本文介绍了如何在SwiftUI中汇总过滤后的核心数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在SwiftUI应用中求和(使用谓词)过滤后的核心数据值?

我有1个名为 NPTransaction 。它有5个属性,我想对名为 value(Integer 64)的属性中的值求和。基本上,它将汇总选定月份的收入值(示例代码中现在将其设置为当前Date(),但稍后将其设置为整个当月)。

I have 1 entity named NPTransaction. It has 5 attributes and I would like to sum values from the attribute named value (Integer 64). Basically, it would sum up values of income in selected month (right now it's set to current Date() in the example code, but later on it will be set to whole current month).

我发现了关于Swift的类似问题,但是我无法使此代码在我的应用中正常工作。
链接到相关问题:如何对存储的核心数据的数字(Int16)求和-Swift 3

I have found similar question regarding Swift, but I cannot make this code to work in my app. Link to related question: How to sum the numbers(Int16) of stored core data - Swift 3

基于链接中的代码,我现在有以下代码:

Based on code from the link, I have following code right now:

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,所以也许有更好和完全不同的方法来解决此问题?

I am just learning Swift and SwiftUI, so maybe there is a better and completely different way of solving this problem?

推荐答案

I在此问题中发现了类似的问题:
(双)获取请求字段之和
我对代码做了一些修改,并提出了以下解决方案:

I have found similar problem in this question: Sum of (double) fetch request field I have modified the code a little and came up with this solution:

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)
    }
}

这篇关于如何在SwiftUI中汇总过滤后的核心数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆