Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 - Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath

I've just updated my Xcode from 8 to 9, and now I noticed when I want to test my project, I got a crash. (before, with Xcode 8, it worked)

The problem is that I have an UICollectionView with cells, which content is downloaded from the internet so the count of them can change. (now it's 5)

When I want to scroll, it crashes immediately with this exception:

2017-09-30 13:31:26.881320+0200 liveExperience[1556:568711] *** Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3694.4.18/UICollectionView.m:1972
2017-09-30 13:31:26.882557+0200 liveExperience[1556:568711] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier - cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:'
*** First throw call stack:
(0x1813ffd38 0x180914528 0x1813ffc0c 0x181d8ec24 0x18b2803c8 0x18a86f344 0x18a86a02c 0x18a80d000 0x1853dd0b4 0x1853e1194 0x18534ff24 0x185376340 0x185377180 0x1813a78b8 0x1813a5270 0x1813a582c 0x1812c62d8 0x183157f84 0x18a873880 0x104a7a800 0x180dea56c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

I checked but the cell identifier is good, the only outlet is good, and now I don't have any idea what is happening.

I append my relevant code snippet here:

func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return games.count
}

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


    guard let imageData = games[indexPath.row].logo as Data? else {
        return UICollectionViewCell()
    }
    cell.gameImageView.image = UIImage(data: imageData)

    return cell

}

I converted my code from Swift 3 to Swift 4.

like image 930
Dániel Grimm Avatar asked Sep 30 '17 11:09

Dániel Grimm


1 Answers

The problem lies in this part of your code:

guard let imageData = games[indexPath.row].logo as Data? else {
    return UICollectionViewCell()
}

You cannot return a UICollectionViewCell without an identifier. You should either remove the elements from your data source that don't have valid image data with filter, or just show a placeholder image for the games that have no image.

like image 123
Tamás Sengel Avatar answered Oct 14 '22 06:10

Tamás Sengel