Mohamed Elgharbawy
Mohamed Elgharbawy

Reputation: 33

NSInternalInconsistencyException error in my code

The following is my code:

import UIKit

class FriendsController: UICollectionViewController {

    private let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.red

        collectionView?.register(FriendCell.self, forCellWithReuseIdentifier: cellId)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)  -> Int{
        return 3
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath)
    }

    }

    class FriendCell: UICollectionViewCell {

    override init(frame: CGRect) {

        super.init(frame: frame)
        setUpViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setUpViews() {
        backgroundColor = UIColor.blue
    }
}

And the following is my error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'the collection view's data source did not return a valid cell from 
-collectionView:cellForItemAtIndexPath: for index path 
<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}'

I'm not exactly sure as to what I did wrong? If anyone could help explain both my error and how to fix it, it would be much appreciated. I'm still a bit new to Swift, and this is my first error I had trouble understanding, especially in the context of my code.

Upvotes: 0

Views: 174

Answers (1)

rmaddy
rmaddy

Reputation: 318794

Your are using the older Swift 2 API for the data source methods.

Instead of:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath)
}

Use:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
}

Upvotes: 1

Related Questions