comparison Simoleon/Helpers/Persistence.swift @ 171:70f0625bfcf1

Merge pull request #17 from denniscm190/development open source project committer: GitHub <noreply@github.com>
author Dennis C. M. <dennis@denniscm.com>
date Tue, 12 Oct 2021 16:17:35 +0200
parents Simoleon/Persistence.swift@ecc58b9cd89d Simoleon/Persistence.swift@1940db1ef321
children
comparison
equal deleted inserted replaced
146:f10b0e188905 171:70f0625bfcf1
1 //
2 // Persistence.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 08/07/2021.
6 //
7
8 import CoreData
9
10 struct PersistenceController {
11 static let shared = PersistenceController()
12
13 static var preview: PersistenceController = {
14 let result = PersistenceController(inMemory: true)
15 let viewContext = result.container.viewContext
16
17 for _ in 0..<10 {
18 let favoritePair = FavoritePair(context: viewContext)
19 favoritePair.baseSymbol = "USD"
20 favoritePair.quoteSymbol = "EUR"
21 }
22
23 do {
24 try viewContext.save()
25 } catch {
26 /*
27 Replace this implementation with code to handle the error appropriately.
28 fatalError() causes the application to generate a crash log and terminate.
29 You should not use this function in a shipping application, although it may be useful during development.
30 */
31 let nsError = error as NSError
32 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
33 }
34 return result
35 }()
36
37 let container: NSPersistentCloudKitContainer
38
39 init(inMemory: Bool = false) {
40 container = NSPersistentCloudKitContainer(name: "Simoleon")
41 container.viewContext.automaticallyMergesChangesFromParent = true
42 container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
43 if inMemory {
44 container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
45 }
46 container.loadPersistentStores(completionHandler: { (storeDescription, error) in
47 if let error = error as NSError? {
48 /*
49 Replace this implementation with code to handle the error appropriately.
50 fatalError() causes the application to generate a crash log and terminate.
51 You should not use this function in a shipping application, although it may be useful during development.
52 */
53
54 /*
55 Typical reasons for an error here include:
56 * The parent directory does not exist, cannot be created, or disallows writing.
57 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
58 * The device is out of space.
59 * The store could not be migrated to the current model version.
60 Check the error message to determine what the actual problem was.
61 */
62 fatalError("Unresolved error \(error), \(error.userInfo)")
63 }
64 })
65 }
66 }