CoreDataStack.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import CoreData
  2. import Foundation
  3. class CoreDataStack: ObservableObject {
  4. init() {}
  5. static let shared = CoreDataStack()
  6. lazy var persistentContainer: NSPersistentContainer = {
  7. let container = NSPersistentContainer(name: "Core_Data")
  8. container.loadPersistentStores(completionHandler: { _, error in
  9. guard let error = error as NSError? else { return }
  10. fatalError("Unresolved error: \(error), \(error.userInfo)")
  11. })
  12. return container
  13. }()
  14. func saveContext() {
  15. let context = persistentContainer.viewContext
  16. context.perform {
  17. if context.hasChanges {
  18. do {
  19. try context.save()
  20. } catch {
  21. // Replace this implementation with code to handle the error appropriately.
  22. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  23. let nserror = error as NSError
  24. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  25. }
  26. }
  27. }
  28. }
  29. func delete(obj: NSManagedObject) {
  30. persistentContainer.viewContext.delete(obj)
  31. }
  32. }