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) {
}
}
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 ?