views:

314

answers:

1

I'm using a UITableView to show some data from an array. This array can be changed at any time by other threads. (I believe that whether the array is mutable, or just replaced entirely, doesn't make a difference.) Access to the array itself is threadsafe.

What's the proper way to ensure thread safety with regard to the tableview? I'm worried, for example, that I might change the array to be shorter just before cellForRowAtIndexPath is called, leading to an NSRangeException.

Should I...

  1. Enforce that the array is only changed on the main thread? (Seems ugly.)
  2. Maintain a shadow array and update this on the main thread through KVO observing?
  3. ??? There must be a better solution...
+1  A: 

From your description, you really have TWO different data sets:

  • The actual data, as it exists in your model
  • The data that's displayed to the user

Thus, you already have, in effect, a 'shadow' array (virtual shadow, which may be stretching the metaphor too far). I'd say your best bet is to formalize this arrangement, and keep a 'display' array that only gets modified in the main thread. In it, you can have objects from your 'real' array; since they're only pointers, you won't be giving up too much memory.

Threading is evil.

Ben Gottlieb
I'm confused...
bentford