Skip to content

Instantly share code, notes, and snippets.

@Pkawa
Last active April 30, 2020 15:55
Show Gist options
  • Save Pkawa/8a65e0286c793c585597d80eda65171d to your computer and use it in GitHub Desktop.
Save Pkawa/8a65e0286c793c585597d80eda65171d to your computer and use it in GitHub Desktop.
Simple Core Data CRUD (Create, Read, Update, Delete) operations (Swift 5, iOS 13)
//
// Copyright © 2020 Piotr Kawa
// The MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import CoreData
// You have to create new Data Model by going "New file..." -> Core Data -> Data Model
// Container name is your .xcdatamodelId filename, in this case it would be just DataModel.xcdatamodelId
let containerName = "DataModel"
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: containerName)
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
// Freebie given by apple - you might want to call this method in applicationWillTerminate method to save your context
// before app gets closed
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)")
}
}
}
//
// Copyright © 2020 Piotr Kawa
// The MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import CoreData
// Here we're grabbing context for our DataModel container from our AppDelegate singleton instance
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let items = loadItems() // here we're loading items from our container, implementation of loadItems() metod is below
//MARK: - Intro to example
// Below you can see basic Create, Read, Update, Delete operations
// "Item" class is an entity that I have defined in .xcdatamodelId file,
// it has 2 attributes - title: String, isDone: Bool - both are required, isDone by default is false.
//MARK: - CREATE example
func addItem() {
// We're creating new item here and set it up
let newItem = Item(context: context)
newItem.title = "Example item"
newItem.isDone = false
// Here we have a new item that lives in the context (kind of like staging area for our persistent container)
// We're calling saveItems() method defined below
saveItems()
}
//MARK: - SAVE OPERATION
func saveItems() {
do {
// We try to save items that exist in the staging area,
// pretty much the same thing as saveContext method in AppDelegate.swift
try context.save()
} catch {
print("Error saving context: \(error)")
}
self.tableView.reloadData()
}
//MARK: - READ OPERATION EXAMPLE
// Simple read operation. Default request parameter returns everything saved in the container
func loadItems(for request: NSFetchRequest<Item> = Item.fetchRequest()) {
do {
items = try context.fetch(request)
} catch {
print("Eror while fetching data from context: \(error)")
}
}
//MARK: READ WITH QUERY OPERATION EXAMPLE
func readItemsUsingQuery() {
let request : NSFetchRequest<Item> = Item.fetchRequest()
// https://academy.realm.io/posts/nspredicate-cheatsheet/
// https://nshipster.com/nspredicate/
request.predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)
// We're sorting items here that our predicate will get for us
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
// loadItems specified above this method
loadItems(for: request)
}
//MARK: UPDATE OPERATION EXAMPLE
func updateItem() {
// Here's a simple update method - we change attribute of our NSManagedObject and call saveItems()
// I'm assung here you already have something in your database, of course (updating first returned item here)
items[0].isDone = !items[0].isDone
saveItems()
// Another example - if we know exact spelling of the attribute, we might as well change things this way
items[0].setValue("New Title", forKey: "title")
saveItems()
}
//MARK: - DELETE OPERATION EXAMPLE
func deleteItem() {
// I'm assung here you already have something in your database, of course (updating first returned item here)
// First we're removing a thing from our context
context.delete(items[0])
// We also have to wipe it out of our items array
items.remove(at: 0)
// Then we save changes that we did in the context area
saveItems()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment