Core Data with SwiftUI Tutorial: Getting Started
In this Core Data with SwiftUI tutorial, you’ll learn to persist data in an app using @State, @Environment and @FetchRequest property wrappers. By Keegan Rush.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Core Data with SwiftUI Tutorial: Getting Started
20 mins
- Getting Started
- Testing FaveFlick’s Persistence
- Setting Up Core Data
- Adding the Core Data stack
- Creating the Data Model
- Relationships and Fetched Properties
- Removing the Old Movie Struct
- Using the New Movie Entity
- Using an Entity’s Attributes in a View
- Using Environment to Access Managed Object Context
- Fetching Objects
- Predicates
- Testing the Results
- Deleting Objects
- Where to Go From Here?
Fetching Objects
Now you’ll learn to display the movies you’ve created. You need to fetch them from the persistent store with a FetchRequest.
At the top of MovieList
, remove the line declaring the movies
array. Replace it with this FetchRequest:
// 1
@FetchRequest(
// 2
entity: Movie.entity(),
// 3
sortDescriptors: [
NSSortDescriptor(keyPath: \Movie.title, ascending: true)
]
// 4
) var movies: FetchedResults<Movie>
When you need to retrieve entities from Core Data, you create a FetchRequest
. Here, you:
- Declare the property using the
@FetchRequest
property wrapper, which lets you use the results directly in your SwiftUI view. - Inside the property wrapper, specify which entity you’d like Core Data to fetch. This will fetch instances of the
Movie
entity. - Add an array of sort descriptors to determine the order of the results. For instance, you could sort the
Movie
s by genre, then by title forMovie
s with the same genre. But here, you simply order by title. - Finally, after the property wrapper, you declare the
movies
property of typeFetchedResults
.
Predicates
This will fetch all Movie
s stored by Core Data. But, what if you need to filter the objects, or only retrieve one specific entity? You can also configure a fetched request with a predicate to limit the results, such as only fetching Movie
s from a certain year or matching a certain genre. To do so, you would add the predicate
parameter at the end of the @FetchRequest
property wrapper, like so:
predicate: NSPredicate(format: "genre contains 'Action'")
There’s no need to add this now, as your fetch request should fetch all Movie
s. But if you want to play around with this then by all means do!
Testing the Results
Build and run. You’ll see your list of movies. Congratulations!
Well, this just gets you back to where you started. To test that the movies are storing to disk, add a few movies and then kill the app by pressing stop in Xcode. Then build and run again. All your movies will still be there!
Deleting Objects
Next, you’ll learn to delete objects. If you swipe left and try to delete a movie, nothing happens. To fix this, replace deleteMovie(at:)
with:
func deleteMovie(at offsets: IndexSet) {
// 1
offsets.forEach { index in
// 2
let movie = self.movies[index]
// 3
self.managedObjectContext.delete(movie)
}
// 4
saveContext()
}
Here’s what’s happening:
- A SwiftUI
List
provides you with anIndexSet
of deletions when you swipe to delete an object in the list. Iterate over theIndexSet
withforEach
. - Get the movie for the current
index
. - Delete the movie from the managed object context.
- Save the context to persist your changes to disk.
Build and run. Then, delete a movie.
You’ve restored all the functionality of the app, and what’s more, it’ll still be there in the morning thanks to Core Data! And you’re done!
Where to Go From Here?
You used Core Data to introduce persistence into a SwiftUI project and store entities to disk. You can download the completed project using the Download Materials button at the top or bottom of this tutorial.
If you want more hands-on experience with Core Data and SwiftUI, check out these tutorials:
Core Data is a huge topic and there’s still a lot to learn. Take a look at Core Data by Tutorials for a deep dive into Core Data using UIKit.
You’ve gone over a fair bit of data flow in this tutorial, but if you’d like to learn more, take a look at WWDC 2019’s Data Flow Through SwiftUI video.
For data flow, as well as everything else you need to become a SwiftUI master, SwiftUI by Tutorials will get you where you need to go.
Getting set up with Core Data is easier than ever before, thanks to SwiftUI. I hope you enjoyed this Core Data with SwiftUI tutorial. If you have any questions or insights to share, please join the forum below.