繁体   English   中英

SWIFT:为tableView计算numberOfRowsInSection时,数组索引超出范围

[英]SWIFT: Array index out of range' when calculating numberOfRowsInSection for tableView

我正在尝试根据上一个屏幕上选择的特定类别类型(例如,卧室装饰,厨房用品,客厅家具等)计算numberOfRowsInSection。 我已经从上一屏幕使用prepareForSegue传递了一个索引,并使用以下内容来选择类别类型:

let category = categoryData[index!]
let categoryType = category.category

然后,我将该类别类型与供应商数据结构进行交叉引用,以在tableView中显示该特定类别的所有供应商。 以下是确定numberOfRowsInSection的函数:

//pulls the data from the Category and Vendor data structures which both contain a "category" item
let categoryData = Data().headerData        
let vendorData = Data().vendorData

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    let category = categoryData[index!]
    let categoryType = category.category

    var count: Int = 0

    for (var i=1; i <= vendorData.count; i++) {

        if vendorData[i].category == categoryType {

            count = count + 1
        }
    }

    return count
}

它可以成功运行,但是一旦进入供应商列表屏幕,它便崩溃并且控制台显示“ Array index out of range”。 我在操场上进行了测试,看来效果很好。

对于整个上下文,一旦确定了正确的行数,我将运行以下命令来填充每个单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("vendorCell", forIndexPath: indexPath) as! VendorSelectionTableViewCell

    let category = categoryData[index!]
    let categoryType = category.category

    let vendorEntry = vendorData[indexPath.row]

    if vendorEntry.category == categoryType {

        cell.vendorName.text = vendorEntry.name

    } else {
         cell.vendorName.text = "No Value"

    }

    return cell
}

Swift数组从0开始计数,而不是从1开始计数。如果将代码更改为

for (var i=0; i < vendorData.count; i++) {
    if vendorData[i].category == categoryType {
        count = count + 1
    }
}

你应该没事的。 我不确定为什么它可以在操场上工作。 也许您的vendorData为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM