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

07. Create the Core Data Stack

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: 06. Extend, Save & Delete Core Data Objects Next episode: 08. Use @FetchRequest to Get Core Data Entries

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've reached locked video content where the transcript will be shown as obfuscated text.

Before we actually try to fetch data from our Core Data database, we need to somehow get a reference to the Core Data stack - specifically the NSManagedObjectContext. This will allow us - as we saw in the last episode - to save and delete content from the database. Note that this isn’t using Combine per se, but instead allows us to use Combine in the next episode.

import CoreData


private enum CoreDataStack {
  
  static var viewContext: NSManagedObjectContext = {
    let container = NSPersistentContainer(name: "ChuckNorrisJokes")

    container.loadPersistentStores { _, error in
      guard error == nil else {
        fatalError("\(#file), \(#function), \(error!.localizedDescription)")
      }
    }

    return container.viewContext
  }()

  
  static func save() {
    guard viewContext.hasChanges else { return }

    do {
      try viewContext.save()
    } catch {
      fatalError("\(#file), \(#function), \(error.localizedDescription)")
    }
  }
}
 JokeView()
        .environment(\.managedObjectContext, CoreDataStack.viewContext)
@Environment(\.scenePhase) var scenePhase
.onChange(of: scenePhase, perform: { newPhase in
      
      if newPhase == .background {
        CoreDataStack.save()
      }
      
      
    })