【问题标题】:[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray[__NSArray0 objectAtIndex:]:空 NSArray 超出范围的索引 0
【发布时间】:2018-04-11 20:11:30
【问题描述】:

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

[__NSArray0 objectAtIndex:]: 空 NSArray 超出范围的索引 0

    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
    }

【问题讨论】:

  • 不要这样做。不要尝试从cellForRowAt 方法加载数据。这是一个非常非常糟糕的主意。该方法应该只做一件事——返回请求的单元格。可以按任何顺序随时请求单元格。

标签: ios swift uitableview


【解决方案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) 函数。有些人确实建议在UIScrollViewscrollViewDidScroll 委托方法中执行此操作。

然后会是这个样子。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多