Last active
November 4, 2017 19:40
-
-
Save barbaramartina/157df92f3d75072e6b5a1bb89ce12527 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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