Integrate Combine Into an App

Aug 5 2021 · Swift 5.4, macOS 11.3, Xcode 12.5

Part 2: Integrate with Core Data & Unit Test

08. Use @FetchRequest to Get Core Data Entries

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 07. Create the Core Data Stack Next episode: 09. Test with Given-When-Then

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

At this point, we’ve written helper methods to save to and delete from the Core Data database. But once we have the data there, we need a way to fetch it from the database and keep the UI up to date.

// On slide: the signature for @FetchRequest
//On slide:
init(entity: NSEntityDescription, sortDescriptors: [NSSortDescriptor], predicate: NSPredicate?, animation: Animation?)
//On slide:
init(sortDescriptors: [NSSortDescriptor], predicate: NSPredicate?, animation: Animation?)
//On slide:
init(fetchRequest: NSFetchRequest<Result>, animation: Animation?)
//On slide:
init(fetchRequest: NSFetchRequest<Result>, transaction: Transaction)
@Environment(\.managedObjectContext) private var viewContext
if decisionState == .liked {
  JokeManagedObject.save(joke: viewModel.joke,
                         inViewContext: viewContext)
}
.sheet(isPresented: $presentSavedJokes) {
        SavedJokesView()
          .environment(\.managedObjectContext, self.viewContext)
      }
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
  sortDescriptors: [NSSortDescriptor(
                        keyPath: \JokeManagedObject.value,
                        ascending: true
                   )],
  animation: .default
) private var jokes: FetchedResults<JokeManagedObject>
ForEach(jokes, id: \.self) { joke in

  Text(self.showTranslation ? joke.translatedValue ?? "N/A"
                            : joke.value ?? "N/A")
    .lineLimit(nil)
}
.onDelete { indices in
  // 2
  self.jokes.delete(at: indices,
                    inViewContext: self.viewContext)
}