无法解决线程1:致命错误:索引超出范围

时间:2018-08-19 13:07:06

标签: swift

我有以下内容:

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]
    }
}

我不断得到:

  

线程1:致命错误:索引超出范围

1 个答案:

答案 0 :(得分:2)

您的numberOfComponents应该是二维数组中外部数组的大小。

您的代码:

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

每次返回4。假设您将数组缩短了,只有3个子数组。之所以会抛出此错误,是因为pickerView期望数组中只有3的行有另外一行,因此它尝试访问第4个索引并发现它无效。

解决方案:

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

对您的numberOfRowsInComponent应用相同的逻辑。

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