Created
November 6, 2017 09:16
-
-
Save josephzhang23/9f48612d6faa2505d34c5d86a5b23855 to your computer and use it in GitHub Desktop.
Core Data Stack
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 | |
| // 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