GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.