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