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

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

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