i am calling
performBatchUpdates({
self.insertItemsAtIndexPaths(indexPathes)
},
completion: {
_ in
})
on a collection view which in controller that is not visible ! there are already another view controllers which pushed above it.
this cause the following error:
Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (12) must be equal to the number of items contained in that section before the update (12), plus or minus the number of items inserted or deleted from that section (12 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'
but that's not true at all because if i am calling performBatchUpdates while the view is visible it will works perfect.
what's happened exactly ?
EDIT: PLEASE note that if i call reloadData it works fine while the view is not visible. what does apples say about that ?
How can i catch this exception. so i could user reloadData instead ?
EDIT: i have printed the following before calling performBachUpdates:
print("visibleCells().count :" + String(self.visibleCells().count))
print("dataModel count:" + String(self.dataArray.count))
here is what i got:
visibleCells().count :0
dataModel count:12
it means that the exception is not true !!
As @rmaddy mentioned in the comments, your issue is that you're not properly updating the data model.
You call insertItemsAtIndexPaths
for indexPathes
(which contains 12 indexes), but your data model starts with 12 indexes and ends with 12 indexes after the batch update. You only need to call insert when you're inserting something in your data model (e.g. after calling something similar to dataModel.insert("whatever", atIndex: 0)
, you may also call insertItemsAtIndexPaths
with index 0).
It doesn't seem to be the case here, since you end up with the same number of elements (12). In this case you need to call reloadData
if you want to refresh the collection view (or don't call anything if data doesn't change)
reloadData
doesn't throw such exceptions, since it doesn't add/remove anything, it will simply get whatever you provide in the data source. insertItemsAtIndexPaths
can animate the changes, so it'll do some checks to see if your data model (whatever you provide in the data source) added the new elements, throwing an exception otherwise.
Catching the exception (using @try/catch) won't get you far, since it'll leave the updates in some weird state, causing further issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With