How to get all SwiftData objects in Swift
A step by step guide on gathering all the existing SwiftData objects of a specific SwiftData Model using SwiftUI, UIKit or AppKit.
The following tutorial has been made available, along with a simple app for demonstrating SwiftData, through the tutorial/swift-data-basics branch on our Open Source Swift Starter Project.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Create the Model
In the project, create the SwiftData model that you wish to get all the objects for.
Step Two: Create the Persistent Container
Create a persistent container and an array to hold the objects using code similar to that below.
Please remember to replace _SwiftDataModelName_ with the name of the model that you created in Step One.
We recommend placing this functionality within a Singleton that acts as a MainActor. If you do not use a MainActor, you will have to use Async/Await patterns.
Step Three: Add Functionality
Add functionality similar that below to the project to fetch all the objects for the model you created in Step One.
We recommend adding this to a file called DataCoordinator+SwiftData.swift, where DataCoordinator is the name of the MainActor singleton that manages the SwiftData.
For more information about what you can do with the FetchDescriptor, we recommend checking out the links below.
Step Four: Fetch All Objects
Call the function defined in Step Three to get all the objects.
Run the app and confirm that the console shows the objects - which may be empty, if none have been added, as shown in the image above.
Looking to learn more about things you can do with SwiftData, Swift or XCode ?
Consult our quick start guide or search our blog to find educational content on learning how to use SwiftData, Swift or XCode.
Frequently Asked Questions (FAQ)
How do I sort the objects by creation date?
To sort the objects by creation date, you must add a date variable to the model (i.e. creationDate) and add the date of creation when creating a new object.
Then, when fetching the objects pass in a SortDescriptor that points to that variable using code similar to that below.
try persistantContainer.mainContext.fetch(FetchDescriptor<SampleSwiftDataModel>(sortBy: [SortDescriptor(.creationDate)]))