0

I never realised this dichotomy before so I need to ask you. Let's say we have some kind of model manager class that will expose an NSArray of objects via public property. This is our model. Now I also have a view controller that shows members of this array in tableview cells. I set this NSArray as a datasource for tableview. But what if I want my model change data in time?

I have two options. 1) Make the array mutable. 2) Replace the instance NSArray with a different instance containing new data.

The issue with option 1 is anybody can change array's content which seems wrong. The issue with option 2 is the tableViewController will happily keep pointing to the original array instance and ignore that the manager class is now pointing to a new instance (since it replaced it's property array instance with one having updated data.).

To sum it up, I want an array instance that can only be mutated from the model manager, but would be immutable to outside world. Which is impossible right? Any ideas how to solve this problem?

Earl Grey
  • 7,426
  • 6
  • 39
  • 59

1 Answers1

2

Either the object managing the array should also be the table view's data source or the table view's data source should always make sure to get a fresh copy of the array from the object managing the array just before the table view reloads its data.

Either way, the array that the table view's datasource is working with should, in the end, be an immutable array, and any time this array is changed, a call to reloadData should immediately be made.

This will prevent the data in the array being modified in the middle of the table view displaying data. It's very problematic if the contents of the array change after numberOfRowsInSection: has been called, for example.

nhgrif
  • 61,578
  • 25
  • 134
  • 173