Skip to content

Instantly share code, notes, and snippets.

@barbaramartina
Last active November 4, 2017 19:40
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 barbaramartina/157df92f3d75072e6b5a1bb89ce12527 to your computer and use it in GitHub Desktop.
Save barbaramartina/157df92f3d75072e6b5a1bb89ce12527 to your computer and use it in GitHub Desktop.
//
// CoreDataStack.swift
// CoreDataShowcase
//
// Created by Barbara Rodeker on 31.10.17.
//
// THIS CLASS CONTAINS ALL THE REQUIRED PROPERTIES THAT NEED TO BE CREATED
// FOR CORE DATA AFTER NSPersistentContainer was added in IOS 10
//
// SWIFT 4
import Foundation
import CoreData
class CoreDataStack: NSObject {
private static let modelName = "YOURMODELNAME"
static var shared = CoreDataStack()
private(set) lazy var container: NSPersistentContainer = {
let description = NSPersistentStoreDescription()
description.type = NSSQLiteStoreType
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
let container = NSPersistentContainer(name: CoreDataStack.modelName)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Saving
func save() {
let context = container.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