hello, i'm looking to use coreData in a pickerview in swift. Here is my code, i don't know why it doesn't work... thanks for your help
import UIKit
import CoreData
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var context : NSManagedObjectContext?
var itemListe : [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
}
override func viewDidAppear(_ animated: Bool) {
lireItem()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
itemListe.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
itemListe[row].value(forKey: "nom") as? String
}
@IBOutlet weak var NomItemTextField: UITextField!
@IBAction func effacerDernierItemAction(_ sender: Any) {
let requete = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
do {
let result = try context!.fetch(requete) as? [NSManagedObject]
let objc = result?.last
context!.delete(objc!)
do {
try context!.save()
print("enregistrement effacé")
} catch {
print("erreur 1")
}
} catch {
print("erreur 2")
}
}
@IBAction func lireItemAction(_ sender: Any) {
lireItem()
}
func lireItem() {
let requete : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Item")
do {
itemListe = try context?.fetch(requete) as! [NSManagedObject]
for r in itemListe {
if let nom = r.value(forKey: "nom"){
print(nom)
}
}
}catch{
print("La requête a échoué")
}
}
@IBAction func enregistrerItemAction(_ sender: Any) {
let nouvelItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context!)
nouvelItem.setValue(NomItemTextField.text, forKey: "nom")
do {
try context?.save()
print("nouvelle item sauvegardé")
}catch{
print("Enregistrement échoué")
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Created
Hello, I'm trying to find an easy way to use "Swift Charts" in Storyboard mode with xcode. I understood how it works with swiftUI but can it be done with storyboard only? THANKS