Search code examples
iosswiftcore-datauicollectionviewcellnsfetchrequest

CoreData: How to display fetched data to UIcollectionView Cell


currently I have this loadCharacters function

    var characterArray = [Character]()

    func loadCharacters(with request: NSFetchRequest<Character> = Character.fetchRequest()) {
        
        do {
            characterArray = try context.fetch(request)
        } catch {
            print("error loading data")
        }        
        collectionView.reloadData()
    }

My question is: How can I pass the fetched Data from there to my subclass CharacterCollectionViewCell and later on use this cell for my

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

any suggestion or any better way to make it works are really appreciated!!


Solution

  • You only need to get the characterArray element corresponding to the indexPath.item and use it to pass it into the cell.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
     -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "characterCell",
     for: indexPath) as! CharacterCollectionViewCell { 
            cell.someLabel.text = characterArray[indexPath.item]
            //...
            return cell
    }
    

    If you have too much data to be passed on it's better to create a model and use it's instance to pass data on to the cell. So, for that firstly create a model.

    struct CharacterCellModel { // all properties... }
    

    Then in your UIViewController sub-class.

    var characterCellModels = [CharacterCellModel]() // append this model
    

    And finally in cellForItemAt:

    cell.characterCellModel = characterCellModels[indexPath.item]