Last active
August 23, 2020 09:17
-
-
Save rahulsingh1101/340279d040631b0213a7f7397ea7a913 to your computer and use it in GitHub Desktop.
Core Data CRUD operation
This file contains 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
To Do CRUD operation in Core Data, we need to do the following things: | |
1. Get reference of NSPersistentContainer. | |
eg. lazy var persistentContainer: NSPersistentContainer (inside Appdelegate) | |
2. Get context from persistentContainer | |
eg. let context = persistentContainer.viewContext (inside Appdelegate) | |
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext (inside ViewController) | |
3. Call fetch, save and delete over this context | |
eg. | |
Save : | |
func saveItem(){ | |
do { | |
try context.save() | |
fetchItems() | |
} catch { | |
print("Error while saving :\(error.localizedDescription)") | |
} | |
} | |
Fetch : | |
func fetchItems(){ | |
let request: NSFetchRequest<Item> = Item.fetchRequest() | |
request.predicate = NSPredicate(format: "name CONTAINS[cd] %@", "some text") // here name is attribute of the Entity | |
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] | |
do { | |
itemsArray = try context.fetch(request) | |
} catch { | |
print("Error while retriving items :\(error)") | |
} | |
} | |
Delete : | |
func deleteItem(item: Item){ | |
context.delete(item) | |
saveItem() | |
} | |
Edit : | |
func update(){ | |
let item = itemsArray[index of managed object that is to be updated] | |
item.name = field.text | |
self.saveItem() | |
} |
This file contains 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
Lets take an example of Items and Category | |
Each category will have list of items. In case of a relationship each Category |
This file contains 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
// | |
// ViewController.swift | |
// CoreDataDemo | |
// | |
// Created by Ajeet N on 23/08/20. | |
// Copyright © 2020 Ajeet N. All rights reserved. | |
// | |
import UIKit | |
import CoreData | |
class ViewController: UIViewController { | |
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext | |
var itemsArray = [Item](){ | |
didSet{ | |
relatedItems.items = itemsArray | |
} | |
} | |
let relatedItems = ItemsTableView() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
loadItem() | |
relatedItems.relatedItemsDelegate = self | |
relatedItems.headerTitles = ["Related Items"] | |
relatedItems.items = itemsArray | |
view.addAutolayoutSubview(relatedItems) | |
NSLayoutConstraint.activate([ | |
relatedItems.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0), | |
relatedItems.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0), | |
relatedItems.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0), | |
relatedItems.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0), | |
]) | |
} | |
@IBAction func addAction(_ sender: UIBarButtonItem) { | |
showAlertWithTextField(itm: nil) | |
} | |
} | |
extension ViewController { | |
func saveItem(){ | |
do { | |
try context.save() | |
loadItem() | |
} catch { | |
print("Error while saving :\(error.localizedDescription)") | |
} | |
} | |
func loadItem(){ | |
let request: NSFetchRequest<Item> = Item.fetchRequest() | |
do { | |
itemsArray = try context.fetch(request) | |
} catch { | |
print("Error while retriving items :\(error)") | |
} | |
} | |
func deleteItem(item: Item){ | |
context.delete(item) | |
saveItem() | |
} | |
} | |
extension ViewController{ | |
func showAlertWithTextField(itm: Item?){ | |
var field = UITextField() | |
let alertController = UIAlertController(title: "Add Category", message: "", preferredStyle: UIAlertController.Style.alert) | |
alertController.addTextField { (textField : UITextField!) -> Void in | |
textField.placeholder = "Enter Category Name" | |
textField.text = itm?.name | |
field = textField | |
} | |
let saveAction = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { alert -> Void in | |
if let ittm = itm{ | |
// While Editing we need to pass the reference of NSManagedObject from the array of fetched NSManagedObject | |
ittm.name = field.text | |
self.saveItem() | |
} else { | |
// While Saving we need to create a new instance of NSManagedObject, set its properties and call context.save() | |
let item = Item(context: self.context) | |
item.name = field.text | |
self.saveItem() | |
} | |
}) | |
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil) | |
alertController.addAction(saveAction) | |
alertController.addAction(cancelAction) | |
self.present(alertController, animated: true, completion: nil) | |
} | |
func removeItem(item: Item){ | |
deleteItem(item: item) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment