Threadsafe UITableView

I am using a UITableView to display some data from an array. This array can be modified at any time by other threads. (I believe that regardless of whether the array is modified or simply completely replaced, it does not matter.) Access to the array itself is thread safe.

What is the correct way to ensure thread safety against a table? I worry, for example, that I can change the array so that it is shorter only before calling cellForRowAtIndexPath, which leads to an NSRangeException.

Should I...

  • Ensure that the array is changed only in the main thread? (Seems ugly.)
  • Maintain shadow array and update it in main stream through KVO observation?
  • ??? There must be a better solution ...
+4
source share
3 answers

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

  • Actual data existing in your model
  • Data displayed to the user

Thus, you already have, in fact, an array of "shadow" (a virtual shadow that stretches the metaphor too much). I would say that it is best to formalize this layout and save the "display" array, which only changes in the main thread. In it you can have objects from your "real" array; since they are just pointers, you won’t refuse too much memory.

Threading is evil.

+6
source

Without knowing more about your application, I think one of the best solutions would be to save the array in the main thread and send it back when another thread needs to make changes. Like this:

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

Of course, you can get a lot more complicated with the send API, but it works with locking and that's it for you. Definitely more elegant than using NSLock. It only works on iOS 4 or later.

+3
source

I have the same situation. I have an array of C ++ objects that provide information in a table view.

As Ben mentioned, I also have a temporary shadow array into which new information is downloaded via the Internet. When the request is complete, I will reconcile this array with the one that supports tableview, which is pretty fast. The question is how to protect the array during this negotiation.

I am performing a reconciliation on the main thread, but I'm not sure what is sufficient to protect against conflicts, especially if the user clicks on a record while waiting for a request; the main object that it is viewing can be deleted.

There is a similar question for your (and mine) here: Update UITableView with threads

but the answers rip off the poster for background operations that are too long, instead of answering his question.

I am going to use NSLock and acquire it before modifying the array and all the delegate methods of the UITableView, unless someone has a better idea.

+1
source

All Articles