UserDefault and EnvironmentObject are crashing preview

I want to have different accounts in an app and save, which one was last used. To do this, I worked with UserDefaults. I also want to share the accounts all over my app in different views. Using EnvironmentObject works just fine for building and running the app, but the preview in canvas does not work.


import SwiftUI
import Combine

final class UserData: ObservableObject {
    @Published var currentUser: User = userData.first{$0.id == UserDefaults.standard.integer(forKey: "currentUser")}! {
        didSet {
            UserDefaults.standard.set(self.currentUser.id, forKey: "currentUser")
        }
    }
    
    @Published var user = userData
}
import SwiftUI

struct ShowTrainingView: View {
    
    @State var showAccounts = false
    
    @EnvironmentObject var userData: UserData
    
    var body: some View {
        NavigationView {
            Text("")
        .navigationBarTitle("Trainieren")
        .navigationBarItems(trailing:
            Button(action: {
                self.showAccounts.toggle()
                print("button pressed")
            }) {
                Image(systemName: "person")
                    .imageScale(.large)
            })
        }
        
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ShowTrainingView()
            .environmentObject(UserData())
    }
}


Does anyone know how to fix this?

Replies

Can you provide some information on the error causing the crash? I've seen instances where it crashed complaining that no appropriate value was found in the environment, but that generally appeared to be a context-switching thing (it appears that environment isn't passed on to items presented modally or pushed onto a navigation stack, you have to propagate those manually).

Actually, I've just seen this now in a simple one-view project. Sounds like a bug in Xcode 11.1. Please file a bug report at https://feedbackassistant.apple.com/ and include the diagnostic information Xcode provides—clicking the “Diagnostics” button above the canvas when an error occurs will open a prompt that allows you to create an archive with useful data. There's a pull-down menu at the bottom left of the dialog, and selecting “Show in Finder” from there (the only option) will create that log for you and then open a Finder window. You can drag that into the attachment area of your bug report.