-
Notifications
You must be signed in to change notification settings - Fork 169
/
Copy pathMockStorage.swift
97 lines (80 loc) · 2.5 KB
/
MockStorage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import Foundation
import CoreData
@testable import Simplenote
/// MockupStorage: InMemory CoreData Stack.
///
class MockStorage {
/// DataModel Name
///
private let name = "Simplenote"
/// Returns the Storage associated with the View Thread.
///
var viewContext: NSManagedObjectContext {
persistentContainer.viewContext
}
/// Persistent Container: Holds the full CoreData Stack
///
private(set) lazy var persistentContainer: NSPersistentContainer = buildPersistentContainer()
/// Nukes the specified Object
///
func delete(_ object: NSManagedObject) {
viewContext.delete(object)
}
/// This method effectively destroys all of the stored data, and generates a blank Persistent Store from scratch.
///
func reset() {
persistentContainer = buildPersistentContainer()
NSLog("💣 [MockupStorage] Stack Destroyed!")
}
/// "Persists" the changes
///
func save() {
try? viewContext.save()
}
}
// MARK: - Descriptors
//
extension MockStorage {
/// Returns the Application's ManagedObjectModel
///
var managedModel: NSManagedObjectModel {
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("[MockupStorage] Could not load model")
}
return mom
}
/// Returns the PersistentStore Descriptor
///
var storeDescription: NSPersistentStoreDescription {
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
return description
}
}
// MARK: - Stack URL's
//
extension MockStorage {
/// Returns the ManagedObjectModel's URL: Pick this up from the Storage bundle. OKAY?
///
var modelURL: URL {
let bundle = Bundle(for: Note.self)
guard let url = bundle.url(forResource: name, withExtension: "momd") else {
fatalError("[MockupStorage] Missing Model Resource")
}
return url
}
}
// MARK: - Private API(s)
//
private extension MockStorage {
func buildPersistentContainer() -> NSPersistentContainer {
let container = NSPersistentContainer(name: name, managedObjectModel: managedModel)
container.persistentStoreDescriptions = [storeDescription]
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
fatalError("[MockupStorage] Fatal Error: \(error) [\(error.userInfo)]")
}
}
return container
}
}