Commit 04737ff044
attempted to fix an assertion in
StoriesViewController due to UITableView
complaining about inconsistent state. The issue
continues to happen. This diff fixes it once and
for all (I hope!).
The scenario that caused a crash prior to
04737ff044 was:
Initially:
models = [a,b,c]
Database changes to [a,b]
reloadStories (loading queue)
newModels = [a,b]
schedule block to run on main queue
Database changes to [x, b]
updateStories (loading queue)
captures self.models, value is [a,b,c] // cue ominous music
load from database
newModels = [x,b]
schedule block to run on main queue; will delete c and change a to x
reloadStories.block runs on main queue
self.models=newModels, value is [a,b]
tableView.reloadData() // UITableView thinks c is deleted
updateStories.block runs on main queue
self.models=newModels, value is [x,b]
tableView.beginUpdates()
tableView.delete(index: 2) // crashes because c was already deleted
Post-04737ff the following scenario causes a
crash:
Initially:
models = [a,b,c]
Database changes to [a,b]
updateStories (loading queue)
load from database
models.set([a,b])
schedule block to run on main queue which will delete c
iOS gets a wild hair and decides to call some
UITableViewDataSource methods.
tableView(_, numberOfRowsInSection:)
return [a,b].count // Now UIKit thinks c is gone
updateStories.block runs on main queue
tableView.beginUpdates()
tableView.delete(index: 2) // crashes because 2 is out of bounds vs number of rows
This commit fixes the problem by ensuring the
read-modify-write that happens in updateStories
never reads older data than what UITableView
has been told about and also that updates to the
model are properly synchronized with
beginUpdates()...endUpdates().
Here's how to think about it: the database goes
through a series of changes. Call them v1, v2,
..., vN.
The loading queue will see each in turn. For each,
it will enqueue a corresponding block on the main
queue to update `model` and tell UITableView about
it.
From the POV of the main queue, each update occurs
in the scope of a UITableView update.
From the POV of the loading queue, each update
reads from exactly the preceding version (from
`trueModels`) and writes to exactly the next
version of `trueModels`.
Therefore, there are no data races.