Skip to content

Instantly share code, notes, and snippets.

@SlappyAUS
Last active October 9, 2020 23:51
Show Gist options
  • Select an option

  • Save SlappyAUS/7e982a9506b7aaa36d32cfaef24b25f7 to your computer and use it in GitHub Desktop.

Select an option

Save SlappyAUS/7e982a9506b7aaa36d32cfaef24b25f7 to your computer and use it in GitHub Desktop.
CoreData #data #coreData
// App Delegate
import CoreData
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
// Controller
import CoreData
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func loadModel() {
let request: NSFetchRequest<Item> = Item.fetchRequest()
do {
itemArray = try context.fetch(request)
} catch {
print("Error fetchin data: \(error)")
}
}
func saveModel() {
do {
try context.save()
} catch {
print("Error saving context: \(error)")
}
tableView.reloadData()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment