Nick Brown
Nick Brown

Reputation: 13

Unable to resolve Thread 1: Fatal error: Index out of range

I have the following:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, NSFetchedResultsControllerDelegate {
    @IBOutlet weak var playerList: UIPickerView!

    var playerData: [[String]] = [[String]]()

    func viewDidLoad() {
        super.viewDidLoad

        playerData = [["1", "2", "3"],["a","b","c"],["i","ii","iii"],["!","@","#"]]

        // Connect data:
        self.playerList.delegate = self
        self.playerList.dataSource = self
    }

    // The number of columns of data
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }

    // The number of rows of data
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return playerData.count
    }

    // The data to return for the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return playerData[component][row]
    }
}

I keep getting:

Thread 1: Fatal error: Index out of range

Upvotes: 0

Views: 203

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11243

Your numberOfComponents should be take size of the outer array in your two dimensional array.

Your code:

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

This returns 4 everytime. Let's say you cut your array short and there are only 3 subarrays. It would throw this error because the pickerView is expecting one more row from your array which has only 3. So it tries to access the 4th index and finds that it's invalid.

Solution:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return playerData.count
}

Applying the same logic to your numberOfRowsInComponent.

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

Upvotes: 2

Related Questions