TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Day 53,Question: How to set up a managed object context in Xcode's SwiftUI previews?

Forums > 100 Days of SwiftUI

Hello, I can do that seting the managed object context in my BookwormApp.swift (what can we call this kind of document- *App.swift?) follow the article.And i want to see the same effect in Xcode's Swift previews, but i didn't know how to inject a managed object context into preview struct. The article said:

Tip: If you’re using Xcode’s SwiftUI previews, you should also inject a managed object context into your preview struct for ContentView.

My code:

struct Day53_03: View {
    @FetchRequest(sortDescriptors: []) var students: FetchedResults<Student>

    @Environment(\.managedObjectContext) var moc

    var body: some View {
        VStack{
            List(students){student in
                Text(student.name ?? "Unknown")
            }

            Button("Add") {
                let firstNames = ["Ginny", "Harry", "Hermione", "Luna", "Ron"]
                let lastNames = ["Granger", "Lovegood", "Potter", "Weasley"]

                let chosenFirstName = firstNames.randomElement()!
                let chosenLastName = lastNames.randomElement()!

                // more code to come
                let student = Student(context: moc)
                student.id = UUID()
                student.name = "\(chosenFirstName) \(chosenLastName)"

                try? moc.save()
            }
        }
    }
}

struct Day53_03_Previews: PreviewProvider {

    static var previews: some View {
        Day53_03()
    }
}

So,i want wo know how to set up a managed object context in preview struct.

Thank you for trying to help me.

3      

I did it this way, although I'm not 100% sure it's correct.

struct ContentView_Previews: PreviewProvider {
    static var dataController = DataController()

    static var previews: some View {
        ContentView()
            .environment(\.managedObjectContext, dataController.container.viewContext)
    }
}

5      

Fly0strich,thank you for your reply, i do it as you said, then it can work what i want.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.