1

我有一个名为 Lessons 的实体,它包括:

@NSManaged public var timeMinutes: Double
@NSManaged public var id: UUID
@NSManaged public var lessonDescription: String
@NSManaged public var date: Dates

“日期”属性通过一对多关系链接到单独的“日期”实体,该实体包括:

@NSManaged public var date: Date

我现在正在尝试显示一个按“日期”计算“timeMinutes”总和的图表。这个 finalArray 将具有以下结构:

struct FinalArray {
    let summedMinutes : Double
    let date : Date
}

我生成(和显示)这个数组的代码如下所示:

import SwiftUI
import SwiftUICharts

struct Test: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: Lessons.allLessonsFetchRequest()) var lessons: FetchedResults<Lessons>

   var finalArray = [FinalArray]()

    init(){
        let allKeys = Set<Date>(lessons{$0.date.date})
        for key in allKeys {
            let sum = lessons.filter({$0.date.date == key}).map({$0.timeMinutes}).reduce(0, +)
            finalArray.append(FinalArray(summedMinutes:sum, date:key))
        }
       finalArray = finalArray.sorted(by: {$0.date < $1.date})
    }

    var body: some View {
        VStack{
               LineView(data:  finalArray.map {$0.summedMinutes}, title: "This graph returns empty").padding()
               LineView(data:  lessons.map {$0.timeMinutes}, title: "This graph works").padding()
        }
    }
}

我在init的第一行收到以下错误:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

有谁知道我该如何解决这个问题?这是什么原因?

如果我在我的视图中对核心数据执行 ForEach,它可以正常工作:

var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}

        ForEach(lessons.map {$0.date.date}, id: \.self) { item in
            VStack{
                Text("\(item, formatter: self.dateFormatter)")
            Text(String(self.lessons.filter{$0.date.date == item}.map {$0.timeMinutes}.reduce(0, +)))
            }
        }

这段代码有效,但这不是我想要的,我想在一个数组中显示总和的 'timeMinutes'。任何想法或解决方法都将受到欢迎!

4

1 回答 1

0

lessons是在视图初始更新时获取的,但尚未init定义,因此尝试在其中使用它会导致崩溃。

这是可能的方法:

   @State private var finalArray = [FinalArray]()

    var body: some View {
        VStack{
               LineView(data:  finalArray.map {$0.summedMinutes}, title: "This graph returns empty").padding()
               LineView(data:  lessons.map {$0.timeMinutes}, title: "This graph works").padding()
        }
        .onAppear {
           let allKeys = Set<Date>(lessons{$0.date.date})
           for key in allKeys {
               let sum = lessons.filter({$0.date.date == key}).map({$0.timeMinutes}).reduce(0, +)
               finalArray.append(FinalArray(summedMinutes:sum, date:key))
           }
          finalArray = finalArray.sorted(by: {$0.date < $1.date})
       }
    }
于 2020-04-20T04:10:29.863 回答