来自Plist文件的numberOfRowsInSection问题

时间:2018-04-10 09:07:56

标签: ios swift uitableview

我正在尝试从plist文件加载数据并按字母顺序过滤它并用它填充表格视图。

let url = Bundle.main.url(forResource: "Names", withExtension: "plist")!
        let data = try! Data(contentsOf: url)
        nameArray =  try! PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String]

        alphabetsSection = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

        for letter in alphabetsSection {
            let predicate = NSPredicate(format: "SELF beginswith[c] %@", letter)
            arrayForSection =  nameArray.filter { predicate.evaluate(with: $0) }
            print(arrayForSection.count)
        }

设置表格视图:

func numberOfSections(in tableView: UITableView) -> Int {
        return alphabetsSection.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return String(describing: alphabetsSection[section])
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayForSection[section].count
    }

应用程序因Thread 1: Fatal error: Index out of range中的numberOfRowsInSection而崩溃。我检查过并发现arrayForSection.count仅适用于for声明,为什么?

2 个答案:

答案 0 :(得分:1)

问题是您是否直接将过滤后的数组分配给arrayForSection。因此,新部分的过滤值将覆盖上一部分的值。

相反,

你应该像为每个部分保留一个过滤的数组一样,如果某个字母没有过滤的值,那么特殊部分的空数组就会出现(部分指的是字母)。

解决此问题:

将过滤后的结果添加到arrayForSection数组中:

    var arrayForSection: [[String]] = []
    for letter in alphabetsSection {
        let predicate = NSPredicate(format: "SELF beginswith[c] %@", letter)
        let filteredResult = nameArray.filter {
            predicate.evaluate(with: $0)
        }
        arrayForSection.append(filteredResult)
    }

为了测试它,我采用了一个阵列:

    let nameArray =  ["Apple","Cherry","Chips","Mango","Magento","Juice","Strawberry"]

结果是:

    [["Apple"], [], ["Cherry", "Chips"], [], [], [], [], [], [], ["Juice"], [], [], ["Mango", "Magento"], [], [], [], [], [], ["Strawberry"], [], [], [], [], [], [], []]

因此,对于每个部分,您将获得一个数组,无论是数据还是空。因此,在arrayForSection[section].count,您将无法获得Thread 1: Fatal error: Index out of range

希望这会有所帮助。

答案 1 :(得分:1)

Dictionary有一种方便的方法来对一组项目进行分组

let dataSource = Dictionary(grouping: nameArray, by: { String($0.prefix(1))})
let alphabetsSection = dataSource.keys.sorted()

相应的表视图数据源和委托方法是

func numberOfSections(in tableView: UITableView) -> Int {
    return alphabetsSection.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return alphabetsSection[section]
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let firstLetter = alphabetsSection[section]
    return dataSource[firstLetter]!.count
}