尝试读取fetchrequest <>时出现运行时错误

时间:2020-04-02 10:31:13

标签: swift core-data swiftui

我想从coredata获取数据,并在图表中显示, 加载应用程序时,init func中的代码存在运行时错误:

让x = self.marks.wrappedValue.count

错误消息是:线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

整个代码如下:

import SwiftUI
import Charts
import CoreData

struct CareDetails: View {
    @Environment(\.managedObjectContext) var context
    let timeSpan=["day","week","month","year"]

    let care:Care
    var marks:FetchRequest<Mark>
    @State private var timeSpanIndex = 0
    @State private var showSheet  = false
    private var  sessions:[Int]=[]
    private var  accuracy:[Double]=[]
    init(care:Care){
        self.care=care
        self.marks = FetchRequest(entity:Mark.entity(),
                                                sortDescriptors: [],
                                                predicate: NSPredicate(format:"care_id == %@",care.id!.uuidString))


        let x=self.marks.wrappedValue.count





    }
    var body: some View {

            VStack{

                        Picker(selection: $timeSpanIndex, label: Text("timeSpan")) {
                            ForEach(0..<timeSpan.count,id:\.self){ idx in
                                Text(self.timeSpan[idx])
                            }
                        }
                        .pickerStyle(SegmentedPickerStyle())
                        .padding()

                LineChartViewSwiftUI(dataLabel: self.care.unit!,sessions: self.sessions,accuracy: self.accuracy)



                 Form{
                    Section{
                        List{
                            NavigationLink(destination:
                            CareDetailsList(marks: self.marks)
                                .environment(\.managedObjectContext, self.context)
                            ){

                                Text("显示所有数据")

                            }
                        }

                    }
                    .multilineTextAlignment(.leading)
                }
            .padding()

            }

    }

}

1 个答案:

答案 0 :(得分:0)

尚未评估。它解决了视图的update()函数调用body的时间。尝试略微改变其结构,然后直接在body中使用它。

struct CareView: View {
    let care: Care
    @FetchRequest var marks: FetchedResult<Mark>

    @State private var timeSpanIndex = 0
    @State private var showSheet  = false

    init(care: Care) {
        self.care = care
        self._marks = FetchRequest(...) // set up as before now. note the `_` though!
    }

    var body: some View {
        // make sure you can ID each `Mark` by something
        ForEach(marks, id: \.id) { mark in
            // create your `MarkView` here
        }
    }
}