iOS development - about MJRefresh refresh crash

Posted by lucidfx on Fri, 03 Jan 2020 13:46:40 +0100

As for MJ, I'm afraid you've heard about it in the industry. It's the first time that bloggers have heard that it's been used for four or five years. After such a long time, MJ is still strong and powerful. Many customized refreshes are expanded through MJ. Bloggers won't explain one by one.
As early as a few years ago, when bloggers just used MJ, they encountered the problem of MJ refresh leading to crash, but they didn't care much. To this day, when they use MJ again, they also encounter the same problem. First, let's see how bloggers write:

    _circleTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight) style:UITableViewStyleGrouped];
    _circleTableView.delegate = self;
    _circleTableView.dataSource = self;
    _circleTableView.estimatedRowHeight = 120;
    _circleTableView.rowHeight = UITableViewAutomaticDimension;
    _circleTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_circleTableView];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // Set auto toggle transparency (auto hide under navigation bar)
    header.automaticallyChangeAlpha = YES;
    // Hide time
    header.lastUpdatedTimeLabel.hidden = YES;
    // Set header
    self.circleTableView.mj_header = header;
    self.circleTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];


#pragma mark - loadNewData
- (void)loadNewData
{
    _page = 1;
    [_tucaoDataArray removeAllObjects];
    [self requestData];
}
#pragma mark - loadMoreData
- (void)loadMoreData
{
    _page++;
    [self requestData];
}

At first glance, it seems that there is nothing wrong with it. Many people use it, but it is precisely this writing method that causes the array to break down when refreshing. The reason is that the data source is deleted before the data is requested in the loadNewData method. If the tableview scrolls during the request, there is no data in the data source. If it is empty, it will directly crash. If the tableview does not scroll, there is a certain chance that it will crash, which is accidental.
The best way is to delete the data after the request, store the new data, and do not delete the data in advance. It's really a low-level mistake.