objective-c - How to correctly use reloadData to refresh tableView or collectionView in iOS development
我想大声告诉你
我想大声告诉你 2017-05-02 09:22:52
0
1
667

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:

  1. The user pulls down the tableview to refresh.

  2. Clear the NSArray that holds the data.

  3. 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.

我想大声告诉你
我想大声告诉你

reply all(1)
迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template