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.

4.5 (57) · 1 Review

Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

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:

  1. Declare the property using the @FetchRequest property wrapper, which lets you use the results directly in your SwiftUI view.
  2. Inside the property wrapper, specify which entity you’d like Core Data to fetch. This will fetch instances of the Movie entity.
  3. Add an array of sort descriptors to determine the order of the results. For instance, you could sort the Movies by genre, then by title for Movies with the same genre. But here, you simply order by title.
  4. Finally, after the property wrapper, you declare the movies property of type FetchedResults.

Predicates

This will fetch all Movies 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 Movies 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 Movies. 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!

List of Created Movies

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:

  1. A SwiftUI List provides you with an IndexSet of deletions when you swipe to delete an object in the list. Iterate over the IndexSet with forEach.
  2. Get the movie for the current index.
  3. Delete the movie from the managed object context.
  4. Save the context to persist your changes to disk.

Build and run. Then, delete a movie.

Attempt to delete a movie in the app

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.