Skip to content

Instantly share code, notes, and snippets.

@HassanSE
Created August 9, 2017 17:54
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 HassanSE/aede91715873e4dbcd52c0e0e6fbd394 to your computer and use it in GitHub Desktop.
Save HassanSE/aede91715873e4dbcd52c0e0e6fbd394 to your computer and use it in GitHub Desktop.
A commonly used CoreData stack
import Foundation
import CoreData
class CoreDataStack {
private let modelName: String
init(modelName: String) {
self.modelName = modelName
}
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
func saveContext () {
guard managedContext.hasChanges else { return }
do {
try managedContext.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment