Hi guys, Today we will learn about how to implement CRUD Operation with CoreData in an ios application.
Before starting to code first we need to know what is CRUD Operation with CoreData –
Core Data is an object graph and persistence framework provided by Apple in the iOS and macOS operating system. It allows data organized by the relation entity-attribute model to be serialized into XML, binary, or SQLite stores.
Data Create –
- create the context from persistent container
- create an entity with a user
- set value for the records for each key
Example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let managedContext = appDelegate!.persistentContainer.viewContext // 2 let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! let person = NSManagedObject(entity: entity, insertInto: managedContext) // 3 person.setValue(name, forKeyPath: "name") // 4 do { try managedContext.save() people.append(person) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } |
Update Data in Coredata-
- prepare the request with a predicate for the entity.
- Fetch record and set new value with key
- save context
Example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let managedContext = appDelegate!.persistentContainer.viewContext let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "PersonDetails") fetchRequest.predicate = NSPredicate(format: "name = %@", cellName) do { let value = try managedContext.fetch(fetchRequest) let valueUpdate = value[index] as! NSManagedObject valueUpdate.setValue(name, forKeyPath: "name") do{ try managedContext.save() } catch{ print(error) } }catch{ print(error) } |
Delete Data in CoreData-
- Prepare the request with a predicate for the entity
- Fetch record and which we want to delete
- make context.delete call
Example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let managedContext = appDelegate!.persistentContainer.viewContext managedContext.delete(people[indexPath.row]) do { try managedContext.save() people.remove(at: indexPath.row) tableViewOutlet.deleteRows(at: [indexPath], with: .fade) } catch { let saveError = error as NSError print(saveError) } |
let’s take an example –
step 1: create a new project, and select use the core data option.
step 2: create a file for core data,
- click on CoreData.xcdatamodeld option
- Click on the Add Entity option
- And add your data which you need to save in core data
step 3: it looks like this
- Click on the plus icon
- enter your data name which you want to store.
code of the example – create a file for the alert box i.e ButtonBar.swift class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import Foundation import UIKit import CoreData class ButtonAlert: UIViewController{ let userDefault = UserDefaults.standard var onEdit : ((_ tableReload : Bool, _ nameText : String, _ ageText : String, _ dob : String ) -> Void)? func alertAction(controller: UIViewController, value: Int, nameString: String){ //1. Create the alert controller. let alert = UIAlertController(title: "", message: "Enter your details", preferredStyle: .alert) //2. Add the text field. You can configure it however you need. alert.addTextField { (nameTextField) -> Void in nameTextField.placeholder = "Enter your name." } alert.addTextField { (ageTextField) -> Void in ageTextField.placeholder = "Enter your age." } alert.addTextField { (dobTextField) -> Void in dobTextField.placeholder = "Enter your date of birth." } //3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (action) -> Void in let textField:String = ((alert?.textFields![0])?.text!)! let textField1:String = ((alert?.textFields![1])?.text!)! let textField2:String = ((alert?.textFields![2])?.text!)! // realm.deleteAll() if textField != "" && textField1 != "" && textField2 != ""{ self.onEdit!(true, textField, textField1, textField2) }else{ print("add your missing details") } })) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) // 4. Present the alert. controller.present(alert, animated: true, completion: nil) } |
2. create a viewController class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var tableViewOutlet: UITableView! var people: [NSManagedObject] = [] var buttonAlertBar = ButtonAlert() let appDelegate = UIApplication.shared.delegate as? AppDelegate override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //1 let managedContext = appDelegate!.persistentContainer.viewContext //2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") //3 do { people = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } @IBAction func plusButton(_ sender: Any) { buttonAlertBar.alertAction(controller: self, value: 0, nameString: "" ) buttonAlertBar.onEdit = { [weak self] (tableReload: Bool, nameText: String, ageText: String, dob: String ) in self?.save(name: nameText, age: ageText, dob: dob) self?.tableViewOutlet.reloadData() } } func save(name: String, age: String, dob: String) { // 1 let managedContext = appDelegate!.persistentContainer.viewContext // 2 let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! let person = NSManagedObject(entity: entity, insertInto: managedContext) // 3 person.setValue(name, forKeyPath: "name") person.setValue(age, forKey: "age") person.setValue(dob, forKey: "dob") // 4 do { try managedContext.save() people.append(person) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } extension ViewController: UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let person = people[indexPath.row] let myCell = tableViewOutlet.dequeueReusableCell(withIdentifier: "CoreDataTVTableViewCell") as! CoreDataTVTableViewCell myCell.nameLabel?.text = "Name :" + (person.value(forKey: "name") as! String) myCell.ageLabel?.text = "Age :" + (person.value(forKeyPath: "age") as! String) myCell.dateOfBirthLabel?.text = "DOB :" + (person.value(forKeyPath: "dob") as! String) myCell.tag = indexPath.row return myCell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let managedContext = appDelegate!.persistentContainer.viewContext managedContext.delete(people[indexPath.row]) do { try managedContext.save() people.remove(at: indexPath.row) tableViewOutlet.deleteRows(at: [indexPath], with: .fade) } catch { let saveError = error as NSError print(saveError) } } } } |
I am attaching some screen of my code for a better understanding
Conclusion –
In this blog, we have discussed how to save, update, create and delete the data in the database by using The CRUD operation with core data
I hope this blog will help you in getting some basic knowledge about the CRUD operation with core data.
Thanks for reading!