BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SwiftData - Using it in a class

Forums > Swift

How do I fetch the SwiftData into a class like I used to fetch CoreData into the class. Changes made to the data in the AppManager were saved.

@Model
final class Item {
    var timestamp: Date

    init(timestamp: Date) {
        self.timestamp = timestamp
    }
}

That would be the model for the app. (Obviously this is very simplified test stuff).

class AppManager: NSObject, ObservableObject,  AVAudioPlayerDelegate {
  // var allItems = a fetch
  // this has to be a class, as I'm not aware of anything besides a class that can be a delegate
}

Every example I've been able to find so far, fetches the data using @Query on a view. I would like the fetch the data into an array in a class. After reading the documentation, there is just one line of code to do the fetch. But how do you set the ModelContainer and the ModelContext in this class?

3      

To fetch data using SwiftData into a class, follow these steps:

  1. Define your data model, conforming to the Model protocol.
  2. Create your AppManager class to manage data.
  3. In the AppManager, you don't need to set up ModelContainer or ModelContext. Use SwiftData's simple API to fetch data directly into your class.

3      

hi Dennis,

this is a little bit of quick guess, and it's not something i have used ... but say your AppManager needs a property to reference the SwiftData modelContainer:

var modelContainer: ModelContainer? // yes, make this optional

when you begin your App, instantiate your AppManager; and then use the onSetp parameter in the .modelContainer(for: ...) modifier to handle a callback. you'll be given a Result type with the modelContainer, at which point you can update the AppManager's reference to the modelContainer.

so something like this

struct MyApp: App {
    let appManager = AppManager()
    var body: some Scene {
        WindowGroup {
            MainView()
                .modelContainer(for: [ModelObject.self], onSetup: handleSetup)
        }
    }

    func handleSetup(result: Result<ModelContainer, Error>) {
        switch result {
            case success(let modelContainer):
                appManager.modelContainer = modelContainer
            case .failure(let error):
                print("error: \(error.localizedDescription)")
        }
    }
}

that could answer your main question, and you can certainly then your AppManager can execute fetch calls on demand using the mainContext of the modelContainer.

however, if you're thinking that you'd like to have an equivalent of Core Data's NSFetchedResultsController for SwiftData, i don't think that's there yet.

hope that's of some interest,

DMG (i am not an AI)

added ater the post: there's probably a more direct way to do this, where you create the modelContainer yourself in advance of having to rely on the .modelContainer modifier to do that for you.

4      

How do we report a post as being possible spam/chatGPT crap?

Reading the last post reads like a chatGPT post and is full of poor/misleading information.

4      

@weo asks

How do we report a post as being possible spam/chatGPT crap?

Send an email to Paul Hudson. His email is listed on the bottom of the page you are looking at right now.

Hint: Do not distract him with conversation, observations, questions, or improvement requests. STAY ON TOPIC.

EMail Subject

The email subject should be DIRECT such as:

Subj: CHAT GPT SPAM in Forum

Message Link

Next Look at the suspected spam message. (Look at your message, too.) Do you SEE the chain link icon? This is a direct link to the offending message. Click the chain icon to copy the link to your clipboard.

FOR EXAMPLE: This is a LINK to your message. https://www.hackingwithswift.com/forums/swift/swiftdata-using-it-in-a-class/23803/24685

Email Message

Your message to Paul should be TO THE POINT.

------ SAMPLE MESSAGE -----------
Paul: I suspect this is a SPAM message from CHAT GPT.
<< PASTE LINK HERE >>

Love and Kisses,
Your fan weo
------- END of SAMPLE MESSAGE -----------

Follow Up

Next: More than likely he will NOT acknowledge your message directly. Instead, he'll nuke the offending message!
Sleep well knowing you improved the world. THEN, you have an important follow up step. RETURN to this message thread and REMOVE YOUR MESSAGE. This is an important step.

Ask Siri to set a reminder for you, incase you are the forgetful type.

Keep Coding

3      

@twostraws  Site AdminHWS+

For future reference: Obelix's sample email is perfect 😅

4      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.