]>
Commit | Line | Data |
---|---|---|
1 | import CoreData | |
2 | ||
3 | struct PersistenceController { | |
4 | static let shared = PersistenceController() | |
5 | ||
6 | static var preview: PersistenceController = { | |
7 | let result = PersistenceController(inMemory: true) | |
8 | let viewContext = result.container.viewContext | |
9 | for _ in 0..<10 { | |
10 | let newMap = Map(context: viewContext) | |
11 | newMap.uuid = UUID() | |
12 | newMap.createdAt = Date() | |
13 | newMap.title = "Map \(newMap.createdAt!.format())" | |
14 | newMap.content = "" | |
15 | } | |
16 | do { | |
17 | try viewContext.save() | |
18 | } catch { | |
19 | let nsError = error as NSError | |
20 | fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
21 | } | |
22 | return result | |
23 | }() | |
24 | ||
25 | let container: NSPersistentCloudKitContainer | |
26 | ||
27 | init(inMemory: Bool = false) { | |
28 | container = NSPersistentCloudKitContainer(name: "Map") | |
29 | ||
30 | container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy | |
31 | container.viewContext.automaticallyMergesChangesFromParent = true | |
32 | ||
33 | if inMemory { | |
34 | container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") | |
35 | } | |
36 | container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
37 | if let error = error as NSError? { | |
38 | fatalError("Unresolved error \(error), \(error.userInfo)") | |
39 | } | |
40 | }) | |
41 | } | |
42 | } |