[__NSArray0 objectAtIndex:]:索引0超出空NSArray的边界

时间:2017-10-30 18:41:34

标签: ios swift uitableview

我从API获取JSON数据并将其显示在tableView中。当用户在最后一行滚动时,下一页将添加到当前数据中。 但是在添加下一页数据时我收到此错误。

[__ NSArray0 objectAtIndex:]:索引0超出空NSArray的界限

    func loadUser(_ currentPage:Int=1){
        APIService.loadUser(currentPage, size: 100, callback: { data in
            if let data = data["user"].arrayValue as [JSON]?{
               self.jsonData?.append(contentsOf: data
               self.tableView.reloadData()
               self.hideLoadingInView(view: self.view)
            }
        })
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.jsonData?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell") as! UserTableViewCell
        cell.user = self.jsonData?[indexPath.row]
        if !isLoading && (indexPath.row == self.jsonData!.count - 1){
           currentPage += 1
           loadUser(currentPage)
        }
       return cell
    }

1 个答案:

答案 0 :(得分:1)

我建议几点可能修复:

  1. 将异常断点添加到项目中,以便更好地调试特定问题。这是非常有用的提示:https://www.natashatherobot.com/xcode-debugging-trick/您可能会发现这有什么问题。
  2. 将API调用响应中的UI操作移动到DispatchQueue.main.async { ... }块中,以确保在主线程上操作UI。否则,它可能会导致奇怪的行为,也可能是您的问题。
  3. 如果您需要从API获取另一个页面到tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)功能,请移动检查。有些人建议您使用scrollViewDidScroll委托的UIScrollView方法。
  4. 进行此操作

    然后它会是这样的。

    func loadUser(_ currentPage:Int=1){
        APIService.loadUser(currentPage, size: 100, callback: { data in
            if let data = data["user"].arrayValue as [JSON]?{
                DispatchQueue.main.async {
                    self.jsonData?.append(contentsOf: data)
                    self.tableView.reloadData()
                    self.hideLoadingInView(view: self.view)
                }
            }
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.jsonData?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if !isLoading && (indexPath.row == self.jsonData!.count - 1){
            currentPage += 1
            loadUser(currentPage)
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell") as! UserTableViewCell
        cell.user = self.jsonData?[indexPath.row]
    
        return cell
    }