Walker
Walker

Reputation: 1147

Collection view index out of range when using refresher

I'm loading an array of images into a CollectionView.

When I activate the refresher, I'm calling this method:

func fetchPics(){
        //Clear array of post
        pics?.removeAll()

            Common.sharedInstance.fetchPics(completion: { (pics) in
            self.pics = pics
            self.collectionView?.reloadData()
            self.refresher.endRefreshing()
        })
    }

The viewDidLoad of the view controller calls this method and everything loads fine; however, calling it from the refresher gives me a:

fatal error: Index out of range

Error in :

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: postCellId, for: indexPath) as! PicCell

        //This is the line that gives me the error
        cell.pic = pics?[(indexPath as NSIndexPath).item]

        return cell
    }

What's the appropriate way of reloading the collection view without getting this error?

Thank you

Upvotes: 1

Views: 989

Answers (2)

Nirav D
Nirav D

Reputation: 72410

Try to put pics?.removeAll() also inside the completion block because your closure code will execute later and if your collectionView might be call cellForItemAt indexPath the you are getting empty array.

 func fetchPics(){

    Common.sharedInstance.fetchPics(completion: { (pics) in

        pics?.removeAll()
        self.pics = pics
        self.collectionView?.reloadData()
        self.refresher.endRefreshing()
    })
}

Note : If you doesn't call removeAll that will also work as of you are initializing the array again with new value.

Upvotes: 3

Walker
Walker

Reputation: 1147

Since I was calling a shared instance of a class in which I make the database calls.. In that class I had created an instance of a pics array in which I was then returning through the completion block.

I wasn't calling the pics?.removeAll inside of the fetchPics method so it was appending to it every time.

Thank you guys for the guidance leading to this answer

Upvotes: 1

Related Questions