代码之家  ›  专栏  ›  技术社区  ›  anuj tiwari

swift 3.0中的索引超出范围错误

  •  0
  • anuj tiwari  · 技术社区  · 7 年前
    func loadMoreData(lBound: Int, uBound: Int){
    
        for i in lBound...uBound{
            tempArray.append(arrayDealPage[i])
        }
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
            self.dealsTable.reloadData()
        })
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
        if arrayDealPage.count != tempArray.count
        {
            let lastItem = tempArray.count - 1
            if indexPath.row == lastItem{
    
                loadMoreData(lBound: tempArray.count, uBound:(tempArray.count-1)+20)
    
            }
        }
    }
    

    我从图像阵列中获得195个数据,我希望一次只显示20个,然后滚动添加另20个。上述代码工作正常,但当我到达大约181或182个单元格时,它会导致索引超出范围错误。195数组计数可以增加,今后如何解决索引超出范围的错误。有人能帮我提前谢谢你吗。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Jabson    7 年前

    您不会检查uBound索引是否在ArrayDalpage数组边界之外。 尝试以下操作:

    func loadMoreData(lBound: Int, uBound: Int){
        // checkeduBound variable never go outside the array bounds
        var checkeduBound = uBound
        if uBound >= arrayDealPage.count {
            checkeduBound = arrayDealPage.count-1
        }
    
        //edited
        if lBound > checkeduBound { return }
    
        //use new checkeduBound here
        for i in lBound...checkeduBound{
            tempArray.append(arrayDealPage[i])
        }
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
            self.dealsTable.reloadData()
        })
    }