Created
August 9, 2017 17:54
-
-
Save HassanSE/aede91715873e4dbcd52c0e0e6fbd394 to your computer and use it in GitHub Desktop.
A commonly used CoreData 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
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