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

SOLVED: Preload app with SwiftData objects?

Forums > Swift

I'm surprised I've not found an answer for this but that just shows how much I do not know what I'm doing. When my SwiftData MacOS Document-based app launches it needs to first check if there is a small set of essential objects present and if not then create them. I have code that queries the modelContext for them and creates them if needed. I do not know how best to invoke that code on startup. The typical first view contains a Table which requires these objects. How is this kind of thing usually done?

  DocumentGroup(
      editing: .moneymavenDocument
      , migrationPlan: MoneyMavenMigrationPlan.self
  ) {
      ContentView()
  }
  .windowStyle(.titleBar)
  .windowToolbarStyle(.unified(showsTitle: true))

Content View is basically managing a set of views:

   var body: some View {
         VStack {
              ZStack {
                  switch selectedView {...

2      

Consider using a better description for ContentView.

When your application's main view loads, you can execute code via the .onAppear() modifier. If your initial database check isn't a huge amount of work, try running it there.

If it's a long, involved process, search the forums and tutorials for async await code. Run your database check in a background thread so you don't bring your interface to a crawl on startup.

DocumentGroup(
      editing: .moneymavenDocument
      , migrationPlan: MoneyMavenMigrationPlan.self
  ) {
      // No! ContentView()
      MyApplicationsMainView()  // <- use a better description
          .onAppear {
              CheckMyDatabaseForInitalValues() // <- Do this after view appears
          }
  }
  .windowStyle(.titleBar)
  .windowToolbarStyle(.unified(showsTitle: true))

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!

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.