Anton Brock
Anton Brock

Reputation: 3

How to solve the error Invalid update: incorrect number of items in section 0 in the collection View on iOS12?

All 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 by which this error occurs (only when deleting, when creating or updating an item 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({
   // here is a request to firebase

   self.db.collection(K.FStore.collectionName!).document((item?.idCard)!).delete() { err in
      if err != nil {
         print("err")
      } else {
         // here removal from the array, which is directly related to CollectionView
         self.cards.remove(at: itemIndex)
      }
    }
 }) {(finished) in
    self.collectionView.reloadData()
 }

 //collection method
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int   {
 // This is where the application crashes. That is, the method above works out completely, but I don’t understand how it works on ios 13, but not on ios 12 ..
     return cards.count 
 }

For anyone who wants to send a question to "Duplicate" or throw a link with the words "SAME RESPONSE" The purpose of the resource is to help with programming questions, and it so happened that I am new to Swift, I really saw and tried to solve my question BEFORE I asked my own.

But no answers gave a result that would fix the error. I ask people with a higher skill to help me, thanks!

Upvotes: 0

Views: 1430

Answers (1)

vadian
vadian

Reputation: 285150

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])
   }
}

Upvotes: 1

Related Questions