Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms Observablecollection throws exception on ios device

In the view model I have a observablecollection which will be created in the constructor. In the method I call the RefreshCommand, which doing the following steps:

  • Clears the existing list (Items.Clear())
  • Calls a webservice to receive new Items (async)
  • uses foreach to add all new Itms to the list

This items will be displayed in a ListView and this works great for Android (simulator and real device) and also for iOS Simulator, but as soon as I deploy it on a real iOS device (in this case iPhone 6), the appliction crashes..

Here is a part of the exception:

"Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (1) 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 (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out). "

I already tried it to move the clear and fill action in the GUIThread and I also tried it with a thread safe collection: https://codetraveler.io/2019/09/11/using-observablecollection-in-a-multi-threaded-xamarin-forms-application/

but the application crashes again and again.. The workaround which works for me is to change the observablecollection to a normal list...

Any ideas why this is happen only on a real device?

like image 518
Nehl-IT Avatar asked Sep 16 '25 10:09

Nehl-IT


1 Answers

I had similar errors, what fixed it for me is reassigning a new ObservableCollection to the bound variable, instead of clearing and adding them one by one. So essentially I created a List of the items to be in the observableCollection, then assigned them like this:

boundVar = new ObservableCollection(list);
like image 111
iSpain17 Avatar answered Sep 18 '25 09:09

iSpain17