This repository has been archived by the owner on Nov 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
DATAStack.swift
517 lines (440 loc) · 22.6 KB
/
DATAStack.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import Foundation
import CoreData
@objc public enum DATAStackStoreType: Int {
case inMemory, sqLite
var type: String {
switch self {
case .inMemory:
return NSInMemoryStoreType
case .sqLite:
return NSSQLiteStoreType
}
}
}
@objc public class DATAStack: NSObject {
private var storeType = DATAStackStoreType.sqLite
private var storeName: String?
private var modelName = ""
private var modelBundle = Bundle.main
private var model: NSManagedObjectModel
private var containerURL = URL.directoryURL()
private let backgroundContextName = "DATAStack.backgroundContextName"
private var isExcludedFromBackup = true
/**
The context for the main queue. Please do not use this to mutate data, use `performInNewBackgroundContext`
instead.
*/
@objc public lazy var mainContext: NSManagedObjectContext = {
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.undoManager = nil
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
context.persistentStoreCoordinator = self.persistentStoreCoordinator
NotificationCenter.default.addObserver(self, selector: #selector(DATAStack.mainContextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: context)
return context
}()
/**
The context for the main queue. Please do not use this to mutate data, use `performBackgroundTask`
instead.
*/
@objc public var viewContext: NSManagedObjectContext {
return self.mainContext
}
private lazy var writerContext: NSManagedObjectContext = {
let context = NSManagedObjectContext(concurrencyType: DATAStack.backgroundConcurrencyType())
context.undoManager = nil
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}()
@objc public private(set) lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model)
try! persistentStoreCoordinator.addPersistentStore(storeType: self.storeType, bundle: self.modelBundle, modelName: self.modelName, storeName: self.storeName, containerURL: self.containerURL, isExcludedFromBackup: isExcludedFromBackup)
return persistentStoreCoordinator
}()
private lazy var disposablePersistentStoreCoordinator: NSPersistentStoreCoordinator = {
let model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
try! persistentStoreCoordinator.addPersistentStore(storeType: .inMemory, bundle: self.modelBundle, modelName: self.modelName, storeName: self.storeName, containerURL: self.containerURL, isExcludedFromBackup: isExcludedFromBackup)
return persistentStoreCoordinator
}()
/**
Initializes a DATAStack using the bundle name as the model name, so if your target is called ModernApp,
it will look for a ModernApp.xcdatamodeld.
*/
@objc public override init() {
let bundle = Bundle.main
if let bundleName = bundle.infoDictionary?["CFBundleName"] as? String {
self.modelName = bundleName
}
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
*/
@objc public init(modelName: String) {
self.modelName = modelName
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
- parameter isExcludedFromBackup: Flag to indicate if the data store should be excluded from backup. Default set to true.
*/
@objc public init(modelName: String, isExcludedFromBackup: Bool) {
self.modelName = modelName
self.isExcludedFromBackup = isExcludedFromBackup
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name, bundle and storeType.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
- parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory
based and doesn't save to disk, while the second one creates a .sqlite file and stores things there.
*/
@objc public init(modelName: String, storeType: DATAStackStoreType) {
self.modelName = modelName
self.storeType = storeType
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name, bundle and storeType.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
- parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in
the main bundle but when using unit tests sometimes your Core Data model could be located where your tests
are located.
- parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory
based and doesn't save to disk, while the second one creates a .sqlite file and stores things there.
*/
@objc public init(modelName: String, bundle: Bundle, storeType: DATAStackStoreType) {
self.modelName = modelName
self.modelBundle = bundle
self.storeType = storeType
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name, bundle, storeType and store name.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
- parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in
the main bundle but when using unit tests sometimes your Core Data model could be located where your tests
are located.
- parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory
based and doesn't save to disk, while the second one creates a .sqlite file and stores things there.
- parameter storeName: Normally your file would be named as your model name is named, so if your model
name is AwesomeApp then the .sqlite file will be named AwesomeApp.sqlite, this attribute allows your to
change that.
*/
@objc public init(modelName: String, bundle: Bundle, storeType: DATAStackStoreType, storeName: String) {
self.modelName = modelName
self.modelBundle = bundle
self.storeType = storeType
self.storeName = storeName
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name, bundle, storeType and store name.
- parameter modelName: The name of your Core Data model (xcdatamodeld).
- parameter bundle: The bundle where your Core Data model is located, normally your Core Data model is in
the main bundle but when using unit tests sometimes your Core Data model could be located where your tests
are located.
- parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory
based and doesn't save to disk, while the second one creates a .sqlite file and stores things there.
- parameter storeName: Normally your file would be named as your model name is named, so if your model
name is AwesomeApp then the .sqlite file will be named AwesomeApp.sqlite, this attribute allows your to
change that.
- parameter containerURL: The container URL for the sqlite file when a store type of SQLite is used.
*/
@objc public init(modelName: String, bundle: Bundle, storeType: DATAStackStoreType, storeName: String, containerURL: URL) {
self.modelName = modelName
self.modelBundle = bundle
self.storeType = storeType
self.storeName = storeName
self.containerURL = containerURL
self.model = NSManagedObjectModel(bundle: self.modelBundle, name: self.modelName)
super.init()
}
/**
Initializes a DATAStack using the provided model name, bundle and storeType.
- parameter model: The model that we'll use to set up your DATAStack.
- parameter storeType: The store type to be used, you have .InMemory and .SQLite, the first one is memory
based and doesn't save to disk, while the second one creates a .sqlite file and stores things there.
*/
@objc public init(model: NSManagedObjectModel, storeType: DATAStackStoreType) {
self.model = model
self.storeType = storeType
let bundle = Bundle.main
if let bundleName = bundle.infoDictionary?["CFBundleName"] as? String {
self.storeName = bundleName
}
super.init()
}
deinit {
NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextWillSave, object: nil)
NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextDidSave, object: nil)
}
/**
Returns a new main context that is detached from saving to disk.
*/
@objc public func newDisposableMainContext() -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = self.disposablePersistentStoreCoordinator
context.undoManager = nil
NotificationCenter.default.addObserver(self, selector: #selector(DATAStack.newDisposableMainContextWillSave(_:)), name: NSNotification.Name.NSManagedObjectContextWillSave, object: context)
return context
}
/**
Returns a background context perfect for data mutability operations. Make sure to never use it on the main thread. Use `performBlock` or `performBlockAndWait` to use it.
Saving to this context doesn't merge with the main thread. This context is specially useful to run operations that don't block the main thread. To refresh your main thread objects for
example when using a NSFetchedResultsController use `try self.fetchedResultsController.performFetch()`.
*/
@objc public func newNonMergingBackgroundContext() -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: DATAStack.backgroundConcurrencyType())
context.persistentStoreCoordinator = self.persistentStoreCoordinator
context.undoManager = nil
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return context
}
/**
Returns a background context perfect for data mutability operations. Make sure to never use it on the main thread. Use `performBlock` or `performBlockAndWait` to use it.
*/
@objc public func newBackgroundContext() -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: DATAStack.backgroundConcurrencyType())
context.name = backgroundContextName
context.persistentStoreCoordinator = self.persistentStoreCoordinator
context.undoManager = nil
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
NotificationCenter.default.addObserver(self, selector: #selector(DATAStack.backgroundContextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: context)
return context
}
/**
Returns a background context perfect for data mutability operations.
- parameter operation: The block that contains the created background context.
*/
@objc public func performInNewBackgroundContext(_ operation: @escaping (_ backgroundContext: NSManagedObjectContext) -> Void) {
let context = self.newBackgroundContext()
let contextBlock: @convention(block) () -> Void = {
operation(context)
}
let blockObject: AnyObject = unsafeBitCast(contextBlock, to: AnyObject.self)
context.perform(DATAStack.performSelectorForBackgroundContext(), with: blockObject)
}
/**
Returns a background context perfect for data mutability operations.
- parameter operation: The block that contains the created background context.
*/
@objc public func performBackgroundTask(operation: @escaping (_ backgroundContext: NSManagedObjectContext) -> Void) {
self.performInNewBackgroundContext(operation)
}
func saveMainThread(completion: ((_ error: NSError?) -> Void)?) {
var writerContextError: NSError?
let writerContextBlock: @convention(block) () -> Void = {
do {
try self.writerContext.save()
if TestCheck.isTesting {
completion?(nil)
}
} catch let parentError as NSError {
writerContextError = parentError
}
}
let writerContextBlockObject: AnyObject = unsafeBitCast(writerContextBlock, to: AnyObject.self)
let mainContextBlock: @convention(block) () -> Void = {
self.writerContext.perform(DATAStack.performSelectorForBackgroundContext(), with: writerContextBlockObject)
DispatchQueue.main.async {
completion?(writerContextError)
}
}
let mainContextBlockObject: AnyObject = unsafeBitCast(mainContextBlock, to: AnyObject.self)
self.mainContext.perform(DATAStack.performSelectorForBackgroundContext(), with: mainContextBlockObject)
}
// Drops the database.
@objc public func drop(completion: ((_ error: NSError?) -> Void)? = nil) {
self.writerContext.performAndWait {
self.writerContext.reset()
self.mainContext.performAndWait {
self.mainContext.reset()
self.persistentStoreCoordinator.performAndWait {
for store in self.persistentStoreCoordinator.persistentStores {
guard let storeURL = store.url else { continue }
try! self.oldDrop(storeURL: storeURL)
}
DispatchQueue.main.async {
completion?(nil)
}
}
}
}
}
// Required for iOS 8 Compatibility.
func oldDrop(storeURL: URL) throws {
let storePath = storeURL.path
let sqliteFile = (storePath as NSString).deletingPathExtension
let fileManager = FileManager.default
self.writerContext.reset()
self.mainContext.reset()
let shm = sqliteFile + ".sqlite-shm"
if fileManager.fileExists(atPath: shm) {
do {
try fileManager.removeItem(at: NSURL.fileURL(withPath: shm))
} catch let error as NSError {
throw NSError(info: "Could not delete persistent store shm", previousError: error)
}
}
let wal = sqliteFile + ".sqlite-wal"
if fileManager.fileExists(atPath: wal) {
do {
try fileManager.removeItem(at: NSURL.fileURL(withPath: wal))
} catch let error as NSError {
throw NSError(info: "Could not delete persistent store wal", previousError: error)
}
}
if fileManager.fileExists(atPath: storePath) {
do {
try fileManager.removeItem(at: storeURL)
} catch let error as NSError {
throw NSError(info: "Could not delete sqlite file", previousError: error)
}
}
}
/// Sends a request to all the persistent stores associated with the receiver.
///
/// - Parameters:
/// - request: A fetch, save or delete request.
/// - context: The context against which request should be executed.
/// - Returns: An array containing managed objects, managed object IDs, or dictionaries as appropriate for a fetch request; an empty array if request is a save request, or nil if an error occurred.
/// - Throws: If an error occurs, upon return contains an NSError object that describes the problem.
@objc public func execute(_ request: NSPersistentStoreRequest, with context: NSManagedObjectContext) throws -> Any {
return try self.persistentStoreCoordinator.execute(request, with: context)
}
// Can't be private, has to be internal in order to be used as a selector.
@objc func mainContextDidSave(_ notification: Notification) {
self.saveMainThread { error in
if let error = error {
fatalError("Failed to save objects in main thread: \(error)")
}
}
}
// Can't be private, has to be internal in order to be used as a selector.
@objc func newDisposableMainContextWillSave(_ notification: Notification) {
if let context = notification.object as? NSManagedObjectContext {
context.reset()
}
}
// Can't be private, has to be internal in order to be used as a selector.
@objc func backgroundContextDidSave(_ notification: Notification) throws {
let context = notification.object as? NSManagedObjectContext
guard context?.name == backgroundContextName else {
return
}
if Thread.isMainThread && TestCheck.isTesting == false {
throw NSError(info: "Background context saved in the main thread. Use context's `performBlock`", previousError: nil)
} else {
let contextBlock: @convention(block) () -> Void = {
self.mainContext.mergeChanges(fromContextDidSave: notification)
}
let blockObject: AnyObject = unsafeBitCast(contextBlock, to: AnyObject.self)
self.mainContext.perform(DATAStack.performSelectorForBackgroundContext(), with: blockObject)
}
}
private static func backgroundConcurrencyType() -> NSManagedObjectContextConcurrencyType {
return TestCheck.isTesting ? .mainQueueConcurrencyType : .privateQueueConcurrencyType
}
private static func performSelectorForBackgroundContext() -> Selector {
return TestCheck.isTesting ? NSSelectorFromString("performBlockAndWait:") : NSSelectorFromString("performBlock:")
}
}
extension NSPersistentStoreCoordinator {
func addPersistentStore(storeType: DATAStackStoreType, bundle: Bundle, modelName: String, storeName: String?, containerURL: URL, isExcludedFromBackup: Bool) throws {
let filePath = (storeName ?? modelName) + ".sqlite"
switch storeType {
case .inMemory:
do {
try self.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch let error as NSError {
throw NSError(info: "There was an error creating the persistentStoreCoordinator for in memory store", previousError: error)
}
break
case .sqLite:
let storeURL = containerURL.appendingPathComponent(filePath)
let storePath = storeURL.path
let shouldPreloadDatabase = !FileManager.default.fileExists(atPath: storePath)
if shouldPreloadDatabase {
if let preloadedPath = bundle.path(forResource: modelName, ofType: "sqlite") {
let preloadURL = URL(fileURLWithPath: preloadedPath)
do {
try FileManager.default.copyItem(at: preloadURL, to: storeURL)
} catch let error as NSError {
throw NSError(info: "Oops, could not copy preloaded data", previousError: error)
}
}
}
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
do {
try self.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch {
do {
try FileManager.default.removeItem(atPath: storePath)
do {
try self.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch let addPersistentError as NSError {
throw NSError(info: "There was an error creating the persistentStoreCoordinator", previousError: addPersistentError)
}
} catch let removingError as NSError {
throw NSError(info: "There was an error removing the persistentStoreCoordinator", previousError: removingError)
}
}
let shouldExcludeSQLiteFromBackup = isExcludedFromBackup && TestCheck.isTesting == false
if shouldExcludeSQLiteFromBackup {
do {
try (storeURL as NSURL).setResourceValue(true, forKey: .isExcludedFromBackupKey)
} catch let excludingError as NSError {
throw NSError(info: "Excluding SQLite file from backup caused an error", previousError: excludingError)
}
}
break
}
}
}
extension NSManagedObjectModel {
convenience init(bundle: Bundle, name: String) {
if let momdModelURL = bundle.url(forResource: name, withExtension: "momd") {
self.init(contentsOf: momdModelURL)!
} else if let momModelURL = bundle.url(forResource: name, withExtension: "mom") {
self.init(contentsOf: momModelURL)!
} else {
self.init()
}
}
}
extension NSError {
convenience init(info: String, previousError: NSError?) {
if let previousError = previousError {
var userInfo = previousError.userInfo
if let _ = userInfo[NSLocalizedFailureReasonErrorKey] {
userInfo["Additional reason"] = info
} else {
userInfo[NSLocalizedFailureReasonErrorKey] = info
}
self.init(domain: previousError.domain, code: previousError.code, userInfo: userInfo)
} else {
var userInfo = [String: String]()
userInfo[NSLocalizedDescriptionKey] = info
self.init(domain: "com.SyncDB.DATAStack", code: 9999, userInfo: userInfo)
}
}
}
extension URL {
fileprivate static func directoryURL() -> URL {
#if os(tvOS)
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last!
#else
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
#endif
}
}