rjgodoy
rjgodoy

Reputation: 121

CollectionView - Fatal error: index out of range - More cells than the view can show

I'm having a CollectionView Fatal error: Index out of range when reloading data with UIRefreshControl.

The collection is configured like this:

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return cloudData.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DataViewCell

    // Configure the cell        
    cell.cloudDataPost = cloudData[indexPath.item]
    return cell
}

The function for reloading data is this:

@objc func loadData() {
    cloudData = [CKRecord]()
    let publicData = CKContainer.default().publicCloudDatabase
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Data", predicate: predicate)
    query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    publicWhisper.perform(query, inZoneWith: nil, completionHandler: { (results, error) in
        if let datos = results {
            self.cloudData = datos
            DispatchQueue.main.async {
                self.collectionView?.reloadData()
                self.refresh.endRefreshing()
            }
        }
    })
}

Everything works fine as long as the number of cells is less than the view can show. With 4 or 7 cells i can reload de collectionView without problem, but when i add another cell resulting in array.count has more cells than the view can show i get the error while refreshing.

The error is this line

Thanks!

Upvotes: 1

Views: 931

Answers (1)

Tim
Tim

Reputation: 9042

You're setting cloudData to an empty array at the top of the loadData() call, without telling the collection view to reload. Remove that line, you're replacing the contents of the array anyway in the perform() call back.

Without reloading the collection view you're creating a mismatch between the collection view and the datasource, resulting in index out of bounds.

Upvotes: 1

Related Questions