Search code examples
swiftuipreview

SwiftUI Preview issue with @State and CoreData


I'm having trouble getting a preview to work with what seems like a pretty simple struct. Customer is a CoreData entity:

struct CustomerDetailView: View {
    
    @Environment(\.managedObjectContext) var moc
    @State var showNewCustomer = false
    
    var customer: Customer
    
    var body: some View {

I've tried almost everything that doesn't work, including this:

struct CustomerDetail_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return
            CustomerDetailView(customer: --Not sure what works here-- ).environment(\.managedObjectContext, context)
    
    }
}

I've tried static let customer = Customer() so that I would have a customer variable to use in the last line, but that did not help.


Solution

  • Preview uses different container for apps, so you can just create new Customer, like

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