Previewing ContentView with CoreData

后端 未结 3 657
长情又很酷
长情又很酷 2020-12-05 08:16

When I try to a SwiftUI ContentView that contains a CoreData fetch request, the preview crashes. Wondering what the correct way to setup the @environment so the preview can

相关标签:
3条回答
  • 2020-12-05 08:47

    The accepted answer does not work for me.

    The essence of the problem is that Preview seems to start with it's own (empty!) persistent store, so you must somehow populate that store with enough objects for all of your Previews to work. I created a class function that populates my database with sample objects IF the database is empty. Also, for each Entity in my model I created a static property that return one of those sample objects to pass as a parameter, as needed, for the specific View being previewed.

    This simplifies the Preview code if the previews use a lot of managed objects:

    struct StringAttributeView_Previews: PreviewProvider {  
        static var previews: some View {
            Preview.database()
            return NavigationView {
                StringAttributeView(attribute: Preview.attribute)
            }
        }
    }
    

    Here is an edited example of my Preview class. Obviously, it is specific to my DataModel class and would have to be tailored to your unique data model, but it should give you the idea of what is needed.

    class Preview {
    
        //MARK: - Populate Preview's Core Data Database
        class func database() {
            if DataModel.isDatabaseEmpty() {
                McDocument.loadSampleData()
            }
        }
    
        //MARK: - For Previews
        class var attribute:
            Attribute { get { return DataModel.allObjects(for: "Attribute").first as! Attribute } }
    }
    
    0 讨论(0)
  • 2020-12-05 08:48

    Credit goes to @ShadowDES - in the Master/Detail template project in Xcode Beta 7 there's a preview that uses Core Data:

    #if DEBUG
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            return ContentView().environment(\.managedObjectContext, context)
        }
    }
    #endif
    

    This works for me in Xcode Beta 5 (my Beta 7 crashes)

    0 讨论(0)
  • 2020-12-05 08:49

    This seems to work for the preview.

    struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environment(.managedObjectContext, PersistenceController.preview.container.viewContext)

    My question, how to make it work on the simulator...

    0 讨论(0)
提交回复
热议问题