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 access the coredata stack. This works fine when building to a simulator but not with a PreviewProvider

import SwiftUI

struct ContentView: View {
    @Environment(\.managedObjectContext) var managedObjectContext

    @FetchRequest(entity: ProgrammingLanguage.entity(), sortDescriptors: [
            NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true),
            NSSortDescriptor(keyPath: \ProgrammingLanguage.creator, ascending: false)
        ]) var languages: FetchedResults<ProgrammingLanguage>

    var body: some View {
        NavigationView {
            List {
                ForEach(languages, id: \.self) { language in
                    Text("Language: \(language.name ?? "Anonymous")")
                }
            }
            .navigationBarTitle("My Languages")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

When I try to pass in argument to the ContentView in ContentView_Previews like so I get the following compiler error.

ContentView(managedObjectContext: managedObjectContext)

Error: Instance member 'managedObjectContext' cannot be used on type 'ContentView_Previews'

Maybe this isn't supported by SwiftUI previews yet? Or is there anything that could fix this?

I'm running Xcode 11 Beta 7.

3
  • 4
    I may have missed it in Beta 6, but with Beta 7, you can now create a new Master / Detail project with Core Data and SwiftUI. It's just the basic timestamp, but it not only works out of the box, but preview works as well. Not sure if a copy / paste of their ContentView_Previews will work in your case, without making modifications, but you should take a peek at it.
    – ShadowDES
    Aug 29, 2019 at 5:33
  • Thanks @ShadowDES, it was exactly what I was looking for
    – bjnortier
    Aug 29, 2019 at 8:47
  • Thanks for the solution @shadowDES!! Works great with Xcode Beta 7 and Catalina beta 7! Good eyes on the Master / Detail project with Core Data and SwiftUI.
    – keydogg
    Aug 29, 2019 at 15:36

2 Answers 2

26

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)

3
  • Crash is fixed for me with 10.15 Beta (19A546d) & Xcode Beta 7 (11M392r).
    – keydogg
    Aug 29, 2019 at 15:34
  • 2
    does that load data from persistent store tho?
    – abjurato
    Sep 13, 2019 at 6:21
  • There should be mention regardless this soultion, Rename all class name, entity name which is same as project name. Apr 4, 2020 at 6:35
4

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 } }
}
2
  • This is what's needed in addition to the accepted answer. Above answer successfully provides access to the context and even lets fetch requests to be executed, but the data base the context has access to is different from that of the simulator. So an additional step to load/create sample data is needed. Jan 6, 2020 at 21:14
  • Actually, the call to Preview.database() performs that additional step to load/create the sample data. I will update my answer with more details.
    – Chuck H
    Mar 31, 2020 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.