UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.