Persistence.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // Persistence.swift
  3. // ydnab
  4. //
  5. // Created by Andrea Franceschini on 20/09/2020.
  6. //
  7. import CoreData
  8. struct PersistenceController {
  9. static let shared = PersistenceController()
  10. // static var preview: PersistenceController = {
  11. // let result = PersistenceController(inMemory: true)
  12. // let viewContext = result.container.viewContext
  13. // for _ in 0..<10 {
  14. // let newItem = Item(context: viewContext)
  15. // newItem.timestamp = Date()
  16. // }
  17. // do {
  18. // try viewContext.save()
  19. // } catch {
  20. // // Replace this implementation with code to handle the error appropriately.
  21. // // 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.
  22. // let nsError = error as NSError
  23. // fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  24. // }
  25. // return result
  26. // }()
  27. let container: NSPersistentContainer
  28. init(inMemory: Bool = false) {
  29. container = NSPersistentContainer(name: "ydnab")
  30. if inMemory {
  31. container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
  32. }
  33. container.loadPersistentStores { (storeDescription, error) in
  34. if let error = error as NSError? {
  35. /*
  36. Typical reasons for an error here include:
  37. * The parent directory does not exist, cannot be created, or disallows writing.
  38. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  39. * The device is out of space.
  40. * The store could not be migrated to the current model version.
  41. Check the error message to determine what the actual problem was.
  42. */
  43. fatalError("Unresolved error \(error), \(error.userInfo)")
  44. }
  45. }
  46. }
  47. }