Mercurial > public > simoleon
comparison Simoleon/Helpers/Persistence.swift @ 156:84137052813d
Refactor code
author | Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com> |
---|---|
date | Sat, 28 Aug 2021 11:15:25 +0100 |
parents | Simoleon/Persistence.swift@ecc58b9cd89d |
children | 35628bac01f5 |
comparison
equal
deleted
inserted
replaced
155:681f2cbe8c7f | 156:84137052813d |
---|---|
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 favorite = Favorite(context: viewContext) | |
19 favorite.currencyPair = "GBP/USD" | |
20 } | |
21 do { | |
22 try viewContext.save() | |
23 } catch { | |
24 /* | |
25 Replace this implementation with code to handle the error appropriately. | |
26 fatalError() causes the application to generate a crash log and terminate. | |
27 You should not use this function in a shipping application, although it may be useful during development. | |
28 */ | |
29 let nsError = error as NSError | |
30 fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
31 } | |
32 return result | |
33 }() | |
34 | |
35 let container: NSPersistentCloudKitContainer | |
36 | |
37 init(inMemory: Bool = false) { | |
38 container = NSPersistentCloudKitContainer(name: "Simoleon") | |
39 container.viewContext.automaticallyMergesChangesFromParent = true | |
40 container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy | |
41 if inMemory { | |
42 container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") | |
43 } | |
44 container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
45 if let error = error as NSError? { | |
46 /* | |
47 Replace this implementation with code to handle the error appropriately. | |
48 fatalError() causes the application to generate a crash log and terminate. | |
49 You should not use this function in a shipping application, although it may be useful during development. | |
50 */ | |
51 | |
52 /* | |
53 Typical reasons for an error here include: | |
54 * The parent directory does not exist, cannot be created, or disallows writing. | |
55 * The persistent store is not accessible, due to permissions or data protection when the device is locked. | |
56 * The device is out of space. | |
57 * The store could not be migrated to the current model version. | |
58 Check the error message to determine what the actual problem was. | |
59 */ | |
60 fatalError("Unresolved error \(error), \(error.userInfo)") | |
61 } | |
62 }) | |
63 } | |
64 } |