Read, update and delete

Swift, Storyboards, Core Data


I have this code that makes an insert with Core Data. How would it be read, update and delete in this specific case?


I have seen a lot of tutorials and each one makes things a bit different. I could not adapt to this case.


(I have already created the data model with the entity Users and the Attrituves name and password. I also have linked the buttons read, update and delete. I am looking for the most bàsic, without tables... Just like the insert I have here. Thank you!)


import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var password: UITextField!
  
    lazy var context : NSManagedObjectContext = {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }()

  
    // INSERT
    @IBAction func button(_ sender: UIButton) {
        guard name.hasText && password.hasText else {
            return
        }

        let user = Users(context: context)
        user.name = self.name.text!
        user.password = self.password.text!
        do {
            try context.save()
            print ("saved")
        } catch {
            print(error)
        }
      
    }

    // READ 
    @IBAction func readButton(_ sender: UIButton) {

    }
   
    // UPDATE
    @IBAction func updateButton(_ sender: UIButton) {

    }
   
    // DELETE 
    @IBAction func deleteButton(_ sender: UIButton) {
       
    }
}

Accepted Reply

they put the context outside the crud

No, they create the context in each func.


But no problem to put it out of each func:


class ViewController: UIViewController {

    var appDelegate: AppDelegate?
    var managedContext: NSManagedObjectContext?
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     
       appDelegate = UIApplication.shared.delegate as? AppDelegate
       managedContext = appDelegate?.persistentContainer.viewContext
    }

Just take care when calling managedContext later to use managedContext?


For instance how to:

- Read: how to call the context (lazy var context) and then read all the pairs name - password that the database has.


I thought I wrote the way to do it for read.

What is not working ?

Replies

As you don't show your CoreData structure, it is nopt possible to say exactly how to do.


But it should be easy if you follow this tutorial:


h ttps://medium.com/@ankurvekariya/core-data-crud-with-swift-4-2-for-beginners-40efe4e7d1cc

The structure is, as I said in the question: the Entity Users and the attributes name (String) and password (String). That is all

Yes, but you don't tell what the keys are…


But, you should have no problem, with such a simple structure, to implement what is described in tutorial.


For instance, to read, will be like (once again, you did not tell what the keys are, so just guess):


        func read() {
          
            // container is set up in the AppDelegates so we need to refer that container.
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
          
            // create a context from this container
            let managedContext = appDelegate.persistentContainer.viewContext
          
            // Prepare the request of type NSFetchRequest  for the entity
            let fetchRequest = NSFetchRequest(entityName: "Users")
          
            do {
                let result = try managedContext.fetch(fetchRequest)
                for data in result as! [NSManagedObject] {     // Do what you need with date, store in a table, …
                    print(data.value(forKey: "username") as! String)
                    print(data.value(forKey: "pawdKey") as! String)
              }
              
            } catch {
                print("Failed")
            }
        }


What is this button exactly ? Specific to a record ? If so, adapt the request as needed

    @IBAction func readButton(_ sender: UIButton) { 
           read()
    }

Note: calling an IBAction "button" may not be the most helful for future maintenance of your code.

I think I understand the tutorial. That information is useful. Thank you. But I do not know how to apply that to the way to do things in the Insert that I show in the question. If I understand, in that case, they put the context outside the crud, they do not do that in each crud. Only once at the beginning.


For instance how to:

- Read: how to call the context (lazy var context) and then read all the pairs name - password that the database has.

- Update: how to call the context and then update the password for the name John (for instance)

- Delete: how to call the context and delete the name John and its password

they put the context outside the crud

No, they create the context in each func.


But no problem to put it out of each func:


class ViewController: UIViewController {

    var appDelegate: AppDelegate?
    var managedContext: NSManagedObjectContext?
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     
       appDelegate = UIApplication.shared.delegate as? AppDelegate
       managedContext = appDelegate?.persistentContainer.viewContext
    }

Just take care when calling managedContext later to use managedContext?


For instance how to:

- Read: how to call the context (lazy var context) and then read all the pairs name - password that the database has.


I thought I wrote the way to do it for read.

What is not working ?

Yes, read works well. Thank you.


Now I am working on this.