Step By Step Process to Save/Fetch/Delete and Sorting the Data From Coredata

Here is the Step By Step Process to Save , Fetch , Delete and Sorting the Data From Coredata :


Step 1: Create the New Project :


Step 2: After Click on the Next , Enter the your Project name and select the Use Coredata option.

Core Data is one of the most popular frameworks provided by Apple for iOS and macOS apps. Core data is used to manage the model layer object in our application. You can treat Core Data as a framework to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database.



Step 3: Now create table view from default view controller and add the bar button item in headerview or navigation controller  through pragmatically or storyboard.



  // create the tableview programatically and appending the data through array to tableview


import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var array1=[coredatModels]()
    let mytableview = UITableView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

 mytableview.frame = CGRect(x:0, y:60, width:self.view.frame.size.width, height:self.view.frame.size.height)
        mytableview.delegate = self
        mytableview.dataSource = self
        self.view.addSubview(mytableview)
        
         }
    
    override func viewWillAppear(_ animated: Bool) {
        getdeta()
        mytableview.reloadData()
        
    }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array1.count
    }
    
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->          UITableViewCell {
        let cell = UITableViewCell()
       
        let task1 = array1[indexPath.row]
        cell.textLabel?.text = "\(task1.name!)"
        return cell
        
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }


}


Step 4: Right Click on the Our Project name and select the New-file :



Step 5: After click on the New file select the cocoatouch and give the your controller name :



Step 6: Create the entity name and add the attributes like string or int as shown below.
Click on the Add entity button, provide the entity name and click on attribute button add the your attributes  Like String and Int or Bool as per our requirement. 



Whatever the attributes we are creating am initialising those attributes in the model. 


class coredatModels: NSObject {
    var name:String!
    init(name:String) {
        self.name=name
    }

}

In the above code name is the attribute which i have created.

Step 7: Create new text field as shown below.


Here is the code to get the below View controller to add the new text fields. Intialize an array for to store the data.

   var name = [String]()


  let textfied = UITextField()
textfied.frame = CGRect(x:40, y:100, width:self.view.frame.size.width-80, height:50)
        textfied.layer.cornerRadius = 10
        textfied.layer.borderWidth = 1
        textfied.placeholder = "AddName"
        textfied.textAlignment = .center
        self.view.addSubview(textfied)
        
        let addbutton = UIButton()
        addbutton.frame = CGRect(x:50, y:200, width:100, height: 50)
        addbutton.setTitle("Add", for:.normal)
        addbutton.backgroundColor = UIColor.gray
        addbutton.layer.borderWidth = 1
        addbutton.layer.cornerRadius = 10
        addbutton.addTarget(self, action:#selector(insertdata), for:.touchUpInside)
        self.view.addSubview(addbutton)
        
        let cancelbutton = UIButton()
        cancelbutton.frame = CGRect(x:addbutton.frame.size.width+addbutton.frame.origin.x+70, y:200, width:100, height: 50)
        cancelbutton.setTitle("cancel", for:.normal)
        cancelbutton.backgroundColor = UIColor.gray
        cancelbutton.layer.borderWidth = 1
        cancelbutton.layer.cornerRadius = 10
        cancelbutton.addTarget(self, action:#selector(canceldata), for:.touchUpInside)
        self.view.addSubview(cancelbutton)



If User clicks on Add button then the text will be updated in the table view.

// get the context and save the data in core data


@objc func insertdata()
 {
   let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let task = Coredata(context:context)
    task.names = textfied.text
    
    (UIApplication.shared.delegate as! AppDelegate).saveContext()
    self.navigationController?.popViewController(animated:true)
    
    
    }
    @objc func canceldata()
  {
    self.navigationController?.popViewController(animated: true)
 }






































If User clicks on Add button then the text will be updated in the table view.  

// To get the data from Core data and Performing the Sorting operation.

//  the below code need to be in default viewcontroller and call the viewillapper method.


func getdeta()
 {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    do{
        self.array1.removeAll()
        let arrays = try context.fetch(Coredata.fetchRequest())
        for k in arrays as! [NSManagedObject]
        {
            let obj=coredatModels(name: k.value(forKey: "names") as! String)
            self.array1.append(obj)
        }
        self.array1 = self.array1.sorted(by: {(a:coredatModels,b:coredatModels) -> Bool in
            (a.name.compare(b.name) == ComparisonResult.orderedAscending)
            
        })
    }
    catch{
        
        print("error")
    }
    
    }


Step 8: Select the required row and swipe the tableview to delete the row.

 

Here is the code to delete the record from Coredata.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    
        if editingStyle==UITableViewCellEditingStyle.delete{
            
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            var requst=[Coredata]()
            
            do {
                requst=try context.fetch(Coredata.fetchRequest())
                for k in requst as[NSManagedObject]
                {
                if self.array1[indexPath.row].name! == k.value(forKey: "names")as! String
                {
                    context.delete(k as NSManagedObject)
                    }
                }
            }
            catch{
                
                print("error")
            }
            
            do {
                try context.save()
                getdeta()
                mytableview.reloadData()
            }
            catch
            {
                print("Error")
            }
            
        }
    }

Thanks For reading hope it will helpful.

Comments