Skip to content

Instantly share code, notes, and snippets.

@andrehsouza
Last active July 2, 2018 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrehsouza/ea1c14b81c1950e2160c6c3ca0f7bc8b to your computer and use it in GitHub Desktop.
Save andrehsouza/ea1c14b81c1950e2160c6c3ca0f7bc8b to your computer and use it in GitHub Desktop.
import UIKit
import CoreData
//MARK: - Core Data stack
class CoreDataStack: NSObject {
static let sharedInstance = CoreDataStack()
static let containerName = "CoreDataExample" //CoreDataExample.xcdatamodeld
private override init() {}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: CoreDataStack.containerName)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
}
// MARK: - Core Data Saving support
extension CoreDataStack {
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment