Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadsafe UITableView

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...
like image 578
Adam Ernst Avatar asked Dec 31 '22 07:12

Adam Ernst


2 Answers

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.

like image 188
Ben Gottlieb Avatar answered Jan 17 '23 05:01

Ben Gottlieb


Without knowing more about your app, I think one of the better solutions would be to keep the array on the main thread and dispatch back to it whenever another thread needs to make a change. Like this:

dispatch_async(dispatch_get_main_queue(), ^{
                [array addObject:object];
                [tableView reloadData];
            });

Of course, you can get much more complex with the dispatch API, but it does handle locking and everything for you. Definitely more elegant than using an NSLock. It does only work on iOS 4 or later though.

like image 34
Jon Shier Avatar answered Jan 17 '23 07:01

Jon Shier