3
votes

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?

2
I think the Clear method could be causing an issue when it cleans the collection. - FreakyAli
Yes the clear method is the problem, but I have to clean the list, before adding new items.. - Nehl-IT
When you use the Clear method it clears the whole collection while notifying the collection changed which causes the above issue the solution is just to assign a new object with the List of correct items! - FreakyAli
One of these two XF issues might be related: issue 7670, issue 7510. - ToolmakerSteve

2 Answers

2
votes

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);
1
votes

Of course you could just set a new ObservableCollection by typing MyCollection = new ObservableCollection(list);. However, this will often result in a flickering of the UI and as already mentioned in a comment: Why are we using an ObservableCollection at all, if we always set a new one?

Another solution that works for me is to use the SourceCache or the SourceList of the DynamicData library: https://github.com/reactiveui/DynamicData

With DynamicData you never work on the ObservableCollection directly. This results in a very performant list where you can add, remove or clear as much as you want and never getting an uncatchable exception on iOS.