Ben Ben - 5 months ago 19
Swift Question

EXEC_BAD_ACCESS populating cell contents in dispatch_async

I'm struggling to get my head around an EXEC_BAD_ACCESS error that I'm getting. The code is as follows:

// Update the cell
dispatch_async(dispatch_get_main_queue(), {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("customCell", forIndexPath: indexPath) as! CustomCollectionViewCell // crash here
cell.image.image = image
if(collectionView.numberOfItemsInSection(0) > indexPath.row) {
self.collectionView.reloadData()
}
})


The code is designed to asynchronously fill in an image in a collectionViewCell after receiving a response from a NSURLSession.dataTaskWithRequest.

The crash is happening on the
let cell =
line, because (I believe) the indexPath no longer exists (because I've changed the contents on the collectionView). I'm not sure how to check that though.

I thought something along the lines of
if let cell =
would work, but I think I'd misunderstood how that works. And from reading other posts, I can see that you can't put the code in a try/catch block either.

Any ideas? Many thanks in advance!

Answer

collectionView.dequeueReusableCellWithReuseIdentifier is used to reuse cells in func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell instead of creating them manually. What you want here is to retrieve the cell, not to reuse it, so you should use: cellForItemAtIndexPath(_ indexPath: NSIndexPath).