【问题标题】:Fatal error: Index out of range when downloading data from the Internet致命错误:从 Internet 下载数据时索引超出范围
【发布时间】:2018-02-07 08:10:10
【问题描述】:

有一个函数可以更新我的 UICollectionView:

@objc func refreshFeed(sender:AnyObject)
{
    fetchWeatherData()
}

private func fetchWeatherData() {
    PostArray = [PostModel]()
    offset = 0
    self.fetchPost()
    self.refreshControl.endRefreshing()
}  

此函数导致 PostArray 集合无效并调用 fetchPost 功能区更新函数:

    func fetchPost(URL: String){
    ApiService.sharedInstance.fetchPost(url: URL, completion: { (Posts: [PostModel]) in
        self.PostArray.append(contentsOf: Posts)
        self.collectionView.reloadData()
    })
}  

更新集合后,函数:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
    cell.PostArray = PostArray[indexPath.item]
    return cell
}  

给出错误消息:Thread 1: Fatal error: Index out of range in line:cell.PostArray = PostArray[indexPath.item]

为什么会这样?数据落入集合中。

对不起我的英语

【问题讨论】:

  • 你在func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int返回什么?
  • 建议您使用cell.PostArray = PostArray[indexPath.row] 作为类名而不是实例名的大写字母名称
  • @GregoryHigley let count = self.PostArray.count return count
  • 这是正确的cell.PostArray = PostArray 否则

标签: ios arrays swift uicollectionview


【解决方案1】:

首先,检查func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 是否返回有效的项目数。

您可以检查PostArray 是否包含给定索引处的项目:

如果 PostArray.indices ~= indexPath.item { cell.postArray = PostArray[indexPath.item] }

您需要确保ApiService.sharedInstance.fetchPost 在主队列上运行completion。如果没有,试试这个:

func fetchPost(网址:字符串){ ApiService.sharedInstance.fetchPost(url: URL, completion: { (Posts: [PostModel]) in self.PostArray.append(contentsOf:帖子) DispatchQueue.main.async { self.collectionView.reloadData() } }) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多