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

SwiftData - model context in a bigger application. How to work with it?

Forums > Swift

Hi all. I have a question about SwiftData and what is the best way of handling and sharing modelContext across bigger app. Currently, when I create an app, I get the following code

var sharedModelContainer: ModelContainer = {...}

var body: some Scene {
    WindowGroup {
        ContentView()
    }
    .modelContainer(sharedModelContainer)
}

but this seems to be ok only for some small app. Lets say I have few views from where I can create or edit model. Should I pass modelContext to that views as a parameter? Or better idea would be assign modelContext as @EnvironmentObject? I am curious how to handle this in proper way. I don't think creating modelContainer in dedicated class (ex. DataAccessor) in every view that will need access to db will be a good idea. Any thought on this? Thanks for any help :)

3      

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!

Reply to this topic…

You need to create an account or log in to reply.

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.