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

Day53 Inject questions about environment variables: managedObjectContext

Forums > SwiftUI

@rong  

I try to inject the managedObjectContext environment variable into the preview entry. Is there any difference between the two methods?

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            // normal code            
            .environment(\.managedObjectContext, DataController.shared.container.viewContext)
            // Code that will crash
           .environment(\.managedObjectContext, DataController().container.viewContext)
    }
}

import Foundation
import CoreData

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "Bookworm")
    static let shared: DataController = DataController()

    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }
}

1      

We can install and use the EnvInject plugin to inject environment variables during the build startup. In the build configuration window, we select the “Inject environment variables” option in the “Add build step” combo box. We can then add the required environment variables in the properties content text box.

1      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free 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.