Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI CoreData crashes preview

I have the following code to draw a list of cars, data stored in coredata.

However the swiftui preview seems to break when I add the line of code that fetches data from the databases.

the error logs tells the following:

PotentialCrashError: test app.app may have crashed

mileage app.app may have crashed. Check ~/Library/Logs/DiagnosticReports for any crash logs from your application.

==================================

| Error Domain=com.apple.dt.ultraviolet.service Code=12 "Rendering service was interrupted" UserInfo={NSLocalizedDescription=Rendering service was interrupted}

this is the code the part where foreach starts and ends causes the error:

import SwiftUI

struct CarListView: View {

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: Car.all()) var cars: FetchedResults<Car>

    var body: some View {

        NavigationView {
            ZStack {
                List {
                    Section(header: Text("Cars")) {
                        ForEach(self.cars, id: \.numberPlate) { car in
                            HStack {
                                VStack(alignment: .leading) {
                                    Text(car.name)
                                    Text(car.numberPlate)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}

struct CarListView_Previews: PreviewProvider {
    static var previews: some View {
        CarListView()
    }
}
like image 308
ARR Avatar asked Mar 04 '23 00:03

ARR


1 Answers

The issue seems to be related to the fact it couldn't somehow get a context which allows to fetch the data in preview mode. By manually doing so for preview mode it fixes the issue.

struct CarListView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return CarListView().environment(\.managedObjectContext, context)

    }
}
like image 133
ARR Avatar answered Mar 05 '23 16:03

ARR