Ninja
Ninja

Reputation: 358

Why dequeueReusableCell(withReuseIdentifier:for:) is nil outside the cellForItemAtIndexPath function scope?

Hi I was trying to modify UICollectionView's cell in NSFetchedResultsController's delegate function

controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)

by means of dequeueReusableCell(withReuseIdentifier:for:) function. But it always returns nil. So I had to use cellForItemAtIndexPath function. But why dequeueReusableCell returns nil. Of course I had registered class before.

 collectionView?.register(MessageCell.self, forCellWithReuseIdentifier: cellId)

Here is code:

   if type == .update {
        print("UPDATE")
        blockOperations.append(BlockOperation(block: {              
           let cell = self.collectionView?.cellForItem(at: indexPath!)
             as! MessageCell          
 //   let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath!)  returns nil. why?
            let friend = self.fetchedResultsController.object(at: indexPath!) as! Friend               
            cell.message = friend.lastMessage

        }))
    }

Upvotes: 0

Views: 502

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100533

First you actually need cellForItem , second it will return a cell if it's currently visible

   collec.cellForItem(at: NSIndexPath.init(row: 0, section: 0  ) as IndexPath)

Upvotes: 1

Shebuka
Shebuka

Reputation: 3228

You must not modify UICollectionView's cell outside of cellForRowAtIndexPath, in NSFetchedResultsController's delegate function edit your underlying data model and call reloadData or reloadRowsAtIndexPaths.

And dequeueReusableCellWithIdentifier must be used only inside cellForRowAtIndexPath.

Upvotes: 0

Related Questions