0

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é")
    }
}
    
    

Damix
  • 3
  • 1
  • Perhaps the picker is calling the delegate methods to get the number of rows before you have made your core data query? Adding some logging or breaking will easily confirm if that is the case. If so, you can trigger the picker to reload after you have read the data using https://developer.apple.com/documentation/uikit/uipickerview/1614380-reloadallcomponents – Geoff Hackworth Apr 28 '23 at 14:15

1 Answers1

0

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()
Ely
  • 8,259
  • 1
  • 54
  • 67
  • Thanks you very much, that works well with an IBOutlet var for the pickerView and pickerView.reloadAllComponent(). – Damix Apr 28 '23 at 18:12