ios - fatal error : Index out of range when downloading data from the Internet

标签 ios arrays swift uicollectionview

有一个函数可以更新我的 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
}  

给出错误消息:线程 1: fatal error :索引超出范围,行:cell.PostArray = PostArray[indexPath.item]

为什么会发生这种情况?数据落入集合中。

对不起我的英语

最佳答案

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

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

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

并且您需要确保 ApiService.sharedInstance.fetchPost 在主队列上运行 completion。如果没有,请尝试以下操作:

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

关于ios - fatal error : Index out of range when downloading data from the Internet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658797/

相关文章:

c - 为什么我不能访问这个 void 类型数组的第二个元素

python - 如何遍历数组数组中的键?

c++ - 对 float 组使用 unique_ptr

ios - 无法在 Swift 中遵循 MKAnnotation 协议(protocol)

ios - 事件指示器未显示

objective-c - 通过发送“类型”来创建工厂类

ios - 逐步下载 Firebase child iOS

swift - 在 Swift 中对继承自 Codable 的类进行子类化导致的崩溃

ios - WCErrorCodeDeliveryFailed : Payload could not be delivered

ios - UITextField attributedPlaceholder 无效