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

SPONSORED Debug 10x faster with Proxyman. Your ultimate tool to capture HTTPs requests/ responses, natively built for iPhone and macOS. You’d be surprised how much you can learn about any system by watching what it does over the network.

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