Search code examples
iosswiftrealmuipickerview

Question mark displayed on UIPickerView instead of Realm data on Xcode 10


I am learning to populate a UIPickerView from Realm database.

The issue is that the UIPickerView displays "?" instead of the data.

Here is my code:

import UIKit
import RealmSwift

class AjouterEmpruntViewController: UIViewController,    UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var PickerViewListeAmis: UIPickerView!

    /* Initialisation de Realm */
    let realm = try! Realm()

    var data:Results<Ami>!
    var listOfFriends:[Ami] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        /* Definition des sources du PickerView */
        self.PickerViewListeAmis.dataSource = self
        self.PickerViewListeAmis.delegate = self

        /* Constitution de la liste de pseudos d'amis pour alimenter le PickerView  */
        self.data = realm.objects(Ami.self)
        self.listOfFriends = Array(self.data)
    }

    @IBAction func btnSaveEmprunt(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true)
    }

    @IBAction func btnCancelEmprunt(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return listOfFriends.count
    }

    private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        print("pseudo = "+listOfFriends[row].pseudo)
        return listOfFriends[row].pseudo
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        print("selected Ami is "+listOfFriends[row].pseudo)
    }
}

I followed this tutorial http://sourcefreeze.com/ios-uipickerview-example-using-swift/

Could you please help me solve the problem?

Here is the result: Issue with ? instead of data 1


Solution

  • You have the wrong method signature of titleForRow so it isn't being called.

    It needs to be:

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    

    not:

    private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    

    Remove private and add the missing _.