Recently, I suddenly discovered that the iOS application I wrote before would occasionally crash when refreshing.
I checked the code and found a bug. The steps that lead to the bug are as follows:
The user pulls down the tableview to refresh.
Clear the NSArray that holds the data.
Get network data and then fill it into NSArray.
Under normal circumstances there is no problem in doing this.
However, if the user drags the tableview during steps 2 and 3, it will crash immediately.
Analyzed the reasons. When I clear the NSArray, the tableView will not automatically call numberOfItemsInSection to get the latest number of data. If it is pulled down at this time, the tableview will call cellForItemAtIndexPath to get a new cell. At this time, because the number of data is 0, cellForItemAtIndexPath access The data will be out of bounds of the array.
So I want to talk about the second step inserted in the middle of the third step, that is, after obtaining the remote data, clear the NSArray, then replace it with the new network data, and then adjust the reloadData refresh.
But this will still have the original bug. Before calling reloadData, the number of NSArray is different from the numberOfItemsInSection obtained by the tableView. It's just that the time interval is shorter than before.
May I ask the experts how you update the data in tableView. How to achieve 100% safety.
As long as the data changes, you should refresh the tableView
Even if you want to clear the content, you can refresh it when you are done