]>
Commit | Line | Data |
---|---|---|
1 | // | |
2 | // Persistence.swift | |
3 | // Map | |
4 | // | |
5 | // Created by Ruben Beltran del Rio on 2/1/21. | |
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 | for _ in 0..<10 { | |
17 | let newMap = Map(context: viewContext) | |
18 | newMap.uuid = UUID() | |
19 | newMap.createdAt = Date() | |
20 | newMap.title = "Map \(newMap.createdAt!.format())" | |
21 | newMap.content = "" | |
22 | } | |
23 | do { | |
24 | try viewContext.save() | |
25 | } catch { | |
26 | // Replace this implementation with code to handle the error appropriately. | |
27 | // 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. | |
28 | let nsError = error as NSError | |
29 | fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
30 | } | |
31 | return result | |
32 | }() | |
33 | ||
34 | let container: NSPersistentCloudKitContainer | |
35 | ||
36 | init(inMemory: Bool = false) { | |
37 | container = NSPersistentCloudKitContainer(name: "Map") | |
38 | if inMemory { | |
39 | container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") | |
40 | } | |
41 | container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
42 | if let error = error as NSError? { | |
43 | // Replace this implementation with code to handle the error appropriately. | |
44 | // 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. | |
45 | ||
46 | /* | |
47 | Typical reasons for an error here include: | |
48 | * The parent directory does not exist, cannot be created, or disallows writing. | |
49 | * The persistent store is not accessible, due to permissions or data protection when the device is locked. | |
50 | * The device is out of space. | |
51 | * The store could not be migrated to the current model version. | |
52 | Check the error message to determine what the actual problem was. | |
53 | */ | |
54 | fatalError("Unresolved error \(error), \(error.userInfo)") | |
55 | } | |
56 | }) | |
57 | } | |
58 | } |