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

Should I create a ModelContext or use the container.mainContext

Forums > SwiftUI

I have many places in my application where I may need to get access to my data based on some filtered criteria. I have created multple classes based on my schema.

To give you a basic idea, here is a simple structure of my data in a one-to-many form:

Connection -> User -> Permits -> PermitData (multiple related tables of data)

my User also has other related data:

User -> Calendars User -> Status etc...

My application can have multiple Connections, which they sync data from that connections server. When they log in, it syncs the USERS from that connection. The user LOGS in and authenticates and then will sync the data. All that data is now synced to that User record. The user can log out, switch connections and never lose that data from the other user. They are independent.

The idea of a simple @Query doesn't work, because everywhere I need to query, I need to have a predicate that is based on the data I am looking for, and the User it is connected to and the connection as well. I have to traverse backwards up the schema tree to get the data I am looking for.

So, I have created classes related to the data in my structure. Right now I need to get a Status Item related to a permit inspection detail record. So, I have a function that will get that data for me, and from what I read from Paul, you can pass around the ModelContainer but not the ModelContext. So, I have changed all my code to pass around a container. When I am inside my class object, which should I use to access the ModelContext and does it matter?

    @MainActor
    func getConsoleInspectionStatusDescription(consoleId : String, consoleVer : String, statusId : String, modelContainer : ModelContainer)
    {
        let modelContext = modelContainer.mainContext  <---- this one?

        let modelContext = ModelContext(modelContainer)  <------ or this one?
    }

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

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.