Trying to use coreData with a pickerview

28 views Asked by At

I'm new in ios developpement and I'm trying to load a pickerView with elements from coreData in an Xcode Project. My code works normaly with an array of defined elements of type String, but not with the array I get with a coreData request. I don't know why it doesn't works. The pickerView just stay empty, See my code below


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
        
    }
    
    
    @IBAction func lireItemAction(_ sender: Any) {
        
        lireItem()
    }
    
    
    func lireItem() {
    
    let requete : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Item")
    
    do {
        
        itemListe = try context?.fetch(requete) as! [NSManagedObject]
     
        }
        
    }catch{
        print("La requête a échoué")
    }
}
    
    

1

There are 1 answers

1
Ely On BEST ANSWER

You must perform a reloadComponent or reloadAllComponents on the UIDataPicker control just after executing the fetch action. In order to do this, your view controller needs a IBOutlet variable to the UIDataPicker control, so that you can use code like this:

itemList = try context?.fetch(request)
pickerView.reloadComponent()