Core Data: Fundamentals

Jul 19 2022 · Swift 5.5, iOS 15.4, Xcode 13.3.1

Part 1: The Core Data Stack

06. Setting Up the 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: 05. Persistent Store Coordinator Next episode: 07. Conclusion

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

Now that you have a better understanding of the moving parts let’s actually write some code.

import CoreData
struct PersistenceController {

}
struct PersistenceController {
  static let shared = PersistenceController()

  static var preview: PersistenceController = {
    let result = PersistenceController(inMemory: true)
    let viewContext = result.container.viewContext
    
    // Dummy data will go here later
    
    do {
      try viewContext.save()
    } catch {
      let nsError = error as NSError
      fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
    return result
  }()
}
  let container: NSPersistentContainer

  init(inMemory: Bool = false) {

	}  
let container = NSPersistentContainer
container = NSPersistentContainer(name: "RocketLaunches")
if inMemory {
  // swiftlint:disable:next force_unwrapping
  container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores { _, error in }
if let error = error as NSError? {
  fatalError("Unresolved error \(error), \(error.userInfo)")
}
  container.viewContext.automaticallyMergesChangesFromParent =
    true

  container.viewContext.name = "viewContext"
  /// - Tag: viewContextMergePolicy
  container.viewContext.mergePolicy = 
    NSMergeByPropertyObjectTrumpMergePolicy
  container.viewContext.undoManager = nil
  container.viewContext.shouldDeleteInaccessibleFaults = true