Skip to content

Instantly share code, notes, and snippets.

@asobolevsky
Created August 27, 2019 15:31
Show Gist options
  • Save asobolevsky/3806fe2691e0781600d0a77543f73407 to your computer and use it in GitHub Desktop.
Save asobolevsky/3806fe2691e0781600d0a77543f73407 to your computer and use it in GitHub Desktop.
final class PersistentStack {
private let storeUrl: URL
private let modelUrl: URL
private lazy var managedObjectModel: NSManagedObjectModel = {
guard let model = NSManagedObjectModel(contentsOf: modelUrl) else {
fatalError("Cannot find model file with URL: \(modelUrl)")
}
return model
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: nil)
} catch {
fatalError("Cannot add persistent store with URL: \(storeUrl)")
}
return persistentStoreCoordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
managedObjectContext.undoManager = UndoManager()
return managedObjectContext
}()
init(with storeUrl: URL, and modelUrl: URL) {
self.storeUrl = storeUrl
self.modelUrl = modelUrl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment