Dom
Dom

Reputation: 569

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:

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?

Upvotes: 4

Views: 1545

Answers (2)

jfmg
jfmg

Reputation: 2666

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.

Upvotes: 1

iSpain17
iSpain17

Reputation: 3053

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

Upvotes: 2

Related Questions