ios - 表复习 - 索引超出范围错误

标签 ios swift uitableview swift3

我已经实现了以下工作正常的代码,它显示正确的数据,在拉取时刷新。但是当快速多次刷新刷新时,它最终会导致 fatal error - 索引超出范围。

这让我发疯,有人能看出我的代码有什么问题吗?

    override func viewDidLoad()
{
    super.viewDidLoad()

    nameArray.removeAll(keepingCapacity: false)
    addressArray.removeAll(keepingCapacity: false)


    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Reloading")
    refresher.addTarget(self, action: #selector(downloadJsonWithURL), for: UIControlEvents.valueChanged)
    tableView.addSubview(refresher)
    self.downloadJsonWithURL()

}


func downloadJsonWithURL()
{
    // Emtpy arrays to avoid index out of range crash
    nameArray.removeAll(keepingCapacity: false)
    addressArray.removeAll(keepingCapacity: false)

    let url = NSURL(string: urlString)

    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in


        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {

            if let projectArray = jsonObj!.value(forKey: "project") as? NSArray {
                for project in projectArray{
                    if let projectDict = project as? NSDictionary {
                        if let name = projectDict.value(forKey: "societe") {
                            self.nameArray.append(name as! String)
                        }
                    }
                    if let projectDict = project as? NSDictionary {
                        if let name = projectDict.value(forKey: "address") {
                            self.addressArray.append(name as! String)
                        }
                    }
                }
            }

            OperationQueue.main.addOperation(
                {
                    self.tableView.reloadData()
                    self.refresher.endRefreshing()
            })
        }
    }).resume()

}

// Count length of array and create number of cells accordingly
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return nameArray.count
}

// Create cell data from arrays
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.projectDesc.text = nameArray[indexPath.row].uppercased()
    cell.projectAddress.text = addressArray[indexPath.row]
    return cell
}

最佳答案

问题是您在收到响应之前从数组中删除了对象。它创建了一个场景,其中您的 numberOfRowsInSection 返回不同的值,当 cellForRowAtIndexPath 被调用时,它在数组中有不同的(零)项,由于索引超出范围问题。这通常是多线程 的问题。

要解决此问题,请仅在成功从 API 调用接收数据时清空数组。为此,您需要在 for project in projectArray{ 上方添加 removeAll 元素的代码。

这让你的代码像:

override func viewDidLoad()
{
    super.viewDidLoad()

    nameArray.removeAll(keepingCapacity: false)
    addressArray.removeAll(keepingCapacity: false)

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Reloading")
    refresher.addTarget(self, action: #selector(downloadJsonWithURL), for: UIControlEvents.valueChanged)
    tableView.addSubview(refresher)
    self.downloadJsonWithURL()
}

func downloadJsonWithURL()
{
    let url = NSURL(string: urlString)

    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in


        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {

            if let projectArray = jsonObj!.value(forKey: "project") as? NSArray {
                nameArray.removeAll(keepingCapacity: false)
                addressArray.removeAll(keepingCapacity: false)

                for project in projectArray{
                    if let projectDict = project as? NSDictionary {
                        if let name = projectDict.value(forKey: "societe") {
                            self.nameArray.append(name as! String)
                        }
                    }
                    if let projectDict = project as? NSDictionary {
                        if let name = projectDict.value(forKey: "address") {
                            self.addressArray.append(name as! String)
                        }
                    }
                }
            }

            OperationQueue.main.addOperation(
                {
                    self.tableView.reloadData()
                    self.refresher.endRefreshing()
            })
        }
    }).resume()
}

关于ios - 表复习 - 索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801127/

相关文章:

ios - UITableview单元格向下滚动不平滑

ios - UITableview contentoffset 有时不起作用

ios - 如何添加额外的表格 View 单元格来处理用户输入?

ios - UIApplication 上名为 -statusBar 或 -statusBarWindow 的应用程序

ios - 在 Swift 中进行应用内购买后,广告不会被删除

ios - 如何获取 UILabel 的当前字体大小

ios - 管理阵列的正确方法

ios - stringByEvaluatingJavaScript(来自 :) return value equivalent

ios - Swift - TableView 单元格按钮执行操作,然后重新加载 TableView

ios - 我应该使用哪个压缩库来在 Objective-C 中正确组装有效的 XLSX 文件?