Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Core Data Stack
//
// CoreDataStack.swift
// ChineseNewWords
//
// Created by 张嘉夫 on 06/11/2017.
// Copyright © 2017 张嘉夫. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
private let modelName: String
lazy var managedContext: NSManagedObjectContext = {
return storeContainer.viewContext
}()
init(modelName: String) {
self.modelName = modelName
}
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: modelName)
container.loadPersistentStores(completionHandler: { (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 error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.