D
D
Darkness2020-06-01 15:34:40
Swift
Darkness, 2020-06-01 15:34:40

How to solve Invalid update: invalid number of items in section 0 error in collectionView on iOS12?

Full error text:


Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (0) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).


The method in which this error occurs (only when deleting, when creating or updating an element from the collection there is no error), this error occurs only on iOS12, on iOS13 and > there is no error.
var cards: [Card] = []

item = self.cards[itemIndex]
   self.collectionView.performBatchUpdates({
 // тут запрос к firebase
       self.db.collection(K.FStore.collectionName!).document((item?.idCard)!).delete() { err in
          if err != nil {
             print("err")
          } else {
// тут удаление из массива, который напрямую связан с CollectionView
             self.cards.remove(at: itemIndex)
          }
     }
}) {(finished) in
     self.collectionView.reloadData()
}


// метод для коллекции 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


 // !! Именно тут приложение падает. То есть метод выше полностью отрабатывает, но я не понимаю, как на ios 13 это работает, а на ios 12 нет.. 
       return cards.count 
}


When debugging, item is there, all the code works.

Attempts to solve the problem:
Found info here: link to SO

Tried to add reloadData()before self.cards.remove(at: itemIndex), but I understand that it's stupid and, of course, did not solve the problem.

I hope this will help to solve the problem, I myself could not think of it yet, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Darkness, 2020-06-02
@AntonBrock

The answer has been given on SO.

Where are the batch updates (plural)?
You don't need performBatchUpdates, the method is only useful for multiple simultaneous updates. Delete the card in the database, on success remove the card from the data source array and delete the item - animated - in the collection view.
My suggestion assumes that the current index path is available which itemIndex derives from

item = self.cards[itemIndex]

self.db.collection(K.FStore.collectionName!).document((item?.idCard)!).delete() { err in
   if let error = err {
      print("An error occurred", error)
   } else {
      self.cards.remove(at: itemIndex)
      self.collectionView.deleteItems(at: [indexPath])
   }
}


Link to SO: answer here
Of course, not the whole answer helped, but it was because of the wrong method that I got an error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question